0

我有一个文件,文件的每一行都是一个 json 对象。例如:

{name:value1,city:value2}
{name:value3,city:value4}
etc.

我想做的是对文件进行逐行搜索。如果值等于搜索到的参数,则更新对象中第二个键的值。例如,如果搜索到的值为 value1,我想将该对象的 city 值更新为参数。这是我到目前为止所拥有的:

//trying first with 'fixed' values, will change to arguments once figured out...
with open('jsonfile.json', "r+", encoding='utf-8') as file:
    for line in file:
        res = json.loads(line)
        test_name = res['name']
        test_city = res['city']
        if test_name == "1":
            res['city'] = "hello"
        json.dump(res, file)

当前代码成功识别 test_name 是否与搜索到的参数匹配,但无论是否更新该值,它都会在文件末尾附加一个新的字典条目。

4

2 回答 2

1

你可以使用文件输入。我写了一个类似于你的代码的代码。使用 json.dumps 因为 print itsel 用单 qoute 更改双 qoute

import fileinput
import json

with fileinput.input('jsonfile.json', inplace=True) as file:
    for line in file:
        res = json.loads(line)
        if res['name'] == '1':
            res['city'] = "hello"
        print('{}'.format(json.dumps(res)), end='\n')        
于 2022-02-28T20:56:52.753 回答
0

请注意,您的输入文件是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"}
于 2022-02-28T20:14:10.837 回答