请注意,您的输入文件是ndjson
. 在此处查看规格
一个简单的函数可以做你想做的事,你可以迭代 NDJSON 中的 JSON,如下所示。
另外,请注意,pprint
不需要,它只是用于输出格式......
蟒蛇代码
import ndjson
from pprint import pprint
def find_and_change(inputData, findKey, findValue, replaceKey, replaceValue):
if findKey in inputData and replaceKey in inputData: # avoid keyerrors
if inputData[findKey] == findValue:
inputData[replaceKey] = replaceValue
return inputData
with open("testdata.ndjson") as infile:
testdata = ndjson.load(infile)
pprint(testdata, indent=4)
print("------------------------------------------------------------")
for item in testdata:
item = find_and_change(item, "name", "value2", "city", "thiswaschanged")
pprint(testdata, indent=4)
with open("outputdata.ndjson", "w") as outfile:
ndjson.dump(testdata, outfile)
测试数据.ndjson
{"name":"value1","city":"city1"}
{"name":"value2","city":"city0"}
{"name":"value2","city":"city1"}
{"name":"value3","city":"city3"}
{"name":"value4","city":"city4"}
输出
[ {'city': 'city1', 'name': 'value1'},
{'city': 'city0', 'name': 'value2'},
{'city': 'city1', 'name': 'value2'},
{'city': 'city3', 'name': 'value3'},
{'city': 'city4', 'name': 'value4'}]
------------------------------------------------------------
[ {'city': 'city1', 'name': 'value1'},
{'city': 'thiswaschanged', 'name': 'value2'},
{'city': 'thiswaschanged', 'name': 'value2'},
{'city': 'city3', 'name': 'value3'},
{'city': 'city4', 'name': 'value4'}]
结果 outputdata.ndjson
{"name": "value1", "city": "city1"}
{"name": "value2", "city": "thiswaschanged"}
{"name": "value2", "city": "thiswaschanged"}
{"name": "value3", "city": "city3"}
{"name": "value4", "city": "city4"}