繁体   English   中英

"python,如何在json文件中找到特定的键值,然后保存整行json文件?"

[英]python, How to find specific key value in json file then save whole line of json file?

我是新手,我需要在json文件中导出特定的键值,我搜索了很多网站但找不到我需要的代码,希望这对我有帮助

我的 json 文件


{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

请记住,输入文件本身<\/em>不是 JSON 文件。 每行都是有效的 JSON,因此必须单独处理。

例如:

import json

with open ('foonew.txt', 'w', encoding='utf-8') as out:
    with open('foo.txt', encoding='utf-8') as j:
        for line in j:
            if (d := json.loads(line))['person']['sex'] == 'male':
                print(json.dumps(d), file=out)

您需要展示您尝试过的内容,以便我们了解您期望的格式。 然而,这是解决它的最简单方法之一 -

我假设您有一个 JSON 文件,其中存储了所有男性和女性的详细信息(每条记录用逗号分隔,并且仅使用双引号""<\/code>而不是单个''<\/code> !您给定的 JSON 文件无效)

从这里您需要导入 json,然后使用 json.load 转换为 python 对象(在这种情况下它将是一个列表),然后对其进行迭代以检查每个字典中的键'sex'<\/code>并进行相应的过滤。 完整代码:

import json

filename = "<filename>.json"
with open(filename, "rt") as file:
    data = json.load(file)

new_data = []
for record in data:
    if record['person']['sex'] == 'male':
        new_data.append(record)

newfile = "<new_filename>.json"
with open(newfile, "wt") as file:
    json.dump(new_data, file)

利用:

import json
s = json.dumps([{'person':{'name':'Silva','sex':'female','age':21}},
{'person':{'name':'LANA','sex':'male','age':28}},
{'person':{'name':'Oliveira','sex':'female','age':35}},
{'person':{'name':'KENN','sex':'male','age':26}}])

如果你有一个 json 文件,那么:

s = 'file_path'

s = pd.read_json(s)
s = s['person'].apply(pd.Series)
s[s['sex']=='male']

在这里,我将 json 转换为 df,然后将每一行转换为单独的列,然后过滤 df。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM