[英]Is there a way to remove certain strings from a JSON File using Python?
我想用另一个字符串替换 JSON 文件中的字符串。 给出的所有解决方案都使用json.load()对 JSON 文件执行任何必要的操作。 但是尝试了很多之后,我找不到替换字符串的方法。 我尝试使用open()和replace()以 Python 读取文件的通常方式读取它,但这不适用于 JSON 文件。
这是 JSON 文件的一部分。
"61" : {
"a" : 0.0,
"b" : 1.0,
"c" : "[ 0, 1 ]"
},
我希望它是:
"61" : {
"a" : 0.0,
"b" : 1.0,
"c" : [ 0, 1 ]
},
这是我用open()和replace()尝试的。
fin = open(JSON_IN)
fout = open(JSON_OUT, "w+")
line_f = fin.readline()
x1 = '"['
while line_f:
print(line_f)
if x1 in line_f:
line_f.replace('\"[', '[')
line_f.replace(']\"', ']')
fout.write(line_f)
else:
fout.write(line_f)
line_f = fin.readline
我希望将“[更改为[ 。有没有办法使用 Python 来做到这一点?
replace()
不会更改变量中的值,但会返回您必须分配给变量的新值
line_f = line_f.replace(...)
如果将"
放在' '
中,则不需要\
,因为它将使用\
搜索文本
代码
fin = open(JSON_IN)
fout = open(JSON_OUT, "w+")
x1 = '"['
for line_f in fin:
print(line_f)
if x1 in line_f:
line_f = line_f.replace('"[', '[').replace(']"', ']')
fout.write(line_f)
如果你想在所有文件中更改它,那么你甚至可以尝试
fin = open(JSON_IN)
fout = open(JSON_OUT, "w+")
text = fin.read()
text = text.replace('"[', '[').replace(']"', ']')
fout.write(text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.