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)
输出:
“颜色” =“黑色”和“ api” =“ demo-application-v1”
“颜色” =“黑色”和“ 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”,
“ key”:“ graph:\” color \“ ='黑色'AND \” api \“ = “ demo-application-v1”节点”,
“ 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 \'节点'}
方法3:
我认为JSON字符串中的Unicode字符可能会造成问题,因此将Unicode字符串转换为普通字符串,然后尝试替换字符串
代码:
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 \'节点'}
答案 0 :(得分:1)
虽然我当然不建议在JSON之类的层次结构中进行任何上下文无关的搜索和替换,但是您的主要问题是,您在JSON文件中搜索的字符串已转义了引号(字面{{{1} }个字符),因此,如果要进行纯文本搜索,则必须考虑这些字符。您可以使用raw strings或自己添加反斜杠,例如:
\
对于您的JSON,这将产生:
{ "a": "b", "key": "abcd nodes", "c": "d" }
(由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))
添加的新行)。