{
"a": "b",
"key": "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes",
"c": "d"
}
< /code>
Следующий код я попробовал: < /p>
string_to_be_replace = "abcd"
string_to = "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes"
string_to_be_identified = "\"color\" = \'black\' AND \"api\" = \'demo-application-v1\'"
string_to_be_identified1 = '"color" = \'black\' AND "api" = \'demo-application-v1\''
print string_to_be_identified
print string_to_be_identified1
print string_to.replace(string_to_be_identified1,string_to_be_replace)
print string.replace(string_to, string_to_be_identified,string_to_be_replace)
< /code>
output: < /p>
"color" = 'black' AND "api" = 'demo-application-v1'
"color" = 'black' AND "api" = 'demo-application-v1'
graph: abcd nodes
graph: abcd nodes
< /code>
< /blockquote>
Это работает нормально и заменяет строку, как и ожидалось, но < /p>
это не тогда, когда я попробовал Следующие подходы
Подход 1:
[*] Открыть файл в режиме чтения,
< /li>
Получить строку по линии и заменить строку < /p>
< /li>
< /ol>
with open(path + '/a.json', 'r') as file:
read_lines = file.readlines()
for line in read_lines:
print line.replace(string_to_be_identified,string_to_be_replace)
file.close()
< /code>
< /blockquote>
output: < /p>
{
"a": "b",
"key": "graph: \"color\" = 'black' AND \"api\" ='demo-application-v1' node",
"c": "d"
}
< /code>
< /blockquote>
Подход 2: < /p>
Открыть файл в режиме чтения, < /p>
< /li>
Поскольку файл A.Json имеет данные JSON, получите загрузку файла JSON, преобразуйте объект JSON в JSON-String и затем замените его. < /< / p>
< /li>
< /ol>
код: < /p>
with open(path + '/a.json', 'r') as file:
loadedJson = json.load(file)
print "z: " + str(loadedJson).replace(string_to_be_identified, string_to_be_replace)
file.close()
< /code>
output: < /p>
z: {u'a': u'b', u'c': u'd', u'key': u'graph: "color" = 'black' AND
"api" = 'demo-application-v1' node'}
Approach 3:
I assume Unicode character in JSON string might be creating a problem so converted Unicode string to normal string and then tried to replace string
code:
def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value)
for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
with open(path + '/a.json', 'r') as file:
loadedJson = json.load(file)
js = byteify(loadedJson)
print "a: " + str(js).replace(string_to_be_identified, string_to_be_replace)
< /code>
output: < /p>
a: {'a': 'b', 'c': 'd', 'key': 'graph: "color" = 'black' AND "api" =
'demo-application-v1' node'}
- python version:2.7.15
- using byteify code from one of the SO answer.
- JSON file is big and cannot do the manual search and replace.
- There is no difference in ' and " in python still tried in above example.
Подробнее здесь: https://stackoverflow.com/questions/524 ... ers-from-f