Skip to content Skip to sidebar Skip to footer

Python: Error While Reading And Replacing String(with Special Characters) From File

a.json file: { 'a': 'b', 'key': 'graph: \'color\' = 'black' AND \'api\' = 'demo-application-v1' nodes', 'c': 'd' } following code I tried: string_to_be_replace = 'abcd' stri

Solution 1:

While I certainly do not recommend any sort of context-unaware search & replace in a hierarchical structure like JSON, your main issue is that the string you're searching for in your JSON file has escaped quotations (literal \ characters) so you have to account for those as well if you want to do plain text search. You can use either raw strings or add the backslashes yourself, something like:

str_search = r"graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1'"# or, if you prefer to manually write down the string instead of declaring it 'raw':# str_search = "graph: \\\"color\\\" = 'black' AND \\\"api\\\" = 'demo-application-v1'"
str_replace = "abcd"withopen("/path/to/your.json", "r") as f:
    for line in f:
        print(line.replace(str_search, str_replace))

Which, for your JSON, will yield:

{

  "a": "b",

  "key": "abcd nodes",

  "c": "d"

}

(Extra new lines added by print).

Post a Comment for "Python: Error While Reading And Replacing String(with Special Characters) From File"