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_identifiedprint string_to_be_identified1print 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 nodesgraph: 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中的 ' 和 " 没有区别。
1 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
虽然我当然不建议在 JSON 等层次结构中进行任何类型的上下文无关搜索和替换,但您的主要问题是您在 JSON 文件中搜索的字符串已转义引号(文字\字符),因此您必须考虑如果您想进行纯文本搜索,也适用于那些。您可以使用原始字符串或自己添加反斜杠,例如:
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"
with open("/path/to/your.json", "r") as f:
for line in f:
print(line.replace(str_search, str_replace))
其中,对于您的 JSON,将产生:
{
"a": "b",
"key": "abcd 节点",
“c”:“d”
}
(由 增加了额外的新行print)。
添加回答
举报
0/150
提交
取消