a.json file:
{
"a": "b",
"key": "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes",
"c": "d"
}
следующий код, который я пробовал:
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)
вывод:
"color" = 'black' AND"api" = 'demo-application-v1'
"color" = 'black' AND "api" = 'demo-application-v1'
график: узлы abcd
график: узлы abcd
Это работает нормально и заменяет строку, как и ожидалось, но
это не так, когда я попробовал следующие подходы
Подход 1:
Открыть файл в режиме чтения,
получить строку за строкой и заменить строку
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()
выход:
{
"a": "b",
"ключ":"graph: \" color \ "= 'black' AND \" api \ "= 'demo-application-v1' node",
"c": "d"
}
Подход 2:
Открыть файл в режиме чтения,
Поскольку файл a.json содержит данные JSONполучить загруженный файл json, преобразовать объект json в строку JSON и затемзамените его.
Код:
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()
вывод:
z: {u'a ': u'b',u'c ': u'd', u'key ': u'graph: "color" = \' black \ 'AND "api" = \' demo-application-v1 \ 'node'}
Подход 3:
Я предполагаю, что символ Unicode в строке JSON может создать проблему, поэтому преобразовал строку Unicode в обычную строку и затем попытался заменить строку
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)
вывод:
a: {'a': 'b', 'c': 'd', 'key': 'graph: "color" = \' black \'AND "api" = \' demo-application-v1 \ 'node'}
- версия Python: 2.7.15
- с использованием байтового кода от одного из SOответ.
- Файл JSON большой и не может выполнить поиск и замену вручную.
- Нет разницы в 'и' в python, все еще пробовали в приведенном выше примере.