a.json 文件:
{
"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'
graph: abcd nodes
graph: abcd nodes
这工作正常并按预期替换字符串但是
当我尝试以下方法时不是
方法一:
以读取模式打开文件,
逐行获取并替换字符串
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",
"key": "graph: \"color\" = 'black' AND \"api\" ='demo-application-v1' node",
"c": "d"
}
方法二:
以阅读模式打开文件,
由于文件 a.json 有 JSON 数据,加载 JSON 文件,将 JSON 对象转换为 JSON-string,然后替换它。
代码:
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 '节点'}
方法三:
我假设 JSON 字符串中的 Unicode 字符可能会产生问题,因此将 Unicode 字符串转换为普通字符串,然后尝试替换字符串
输出:
a: {'a': 'b', 'c': 'd', 'key': 'graph: "color" = 'black' AND "api" = 'demo-application-v1' node'}
蟒蛇版本:2.7.15
使用来自 SO 答案之一的 byteify 代码。
JSON 文件很大,无法进行手动搜索和替换。
在上面的例子中仍然尝试过的python中的 ' 和 " 没有区别。
哈士奇WWW
相关分类