如何使用给定的键将文本文件转换为json?

2024-06-26 14:39:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个文本文件:

[{"Keywords":"softeware developer","Results":[{"categoryId":"1234","categoryName":"lead developer","score":"0.7412536859512329"},{"categoryId":"1657","categoryName":"developer consultant","score":"0.6560295867919922"},{"categoryId":"2324","categoryName":"etl developer","score":"0.6531170797348023"},{"categoryId":"2632","categoryName":"oracle developer","score":"0.6264872598648071"},{"categoryId":"1232","categoryName":"sharepoint developer","score":"0.6262540578842163"}]}]

我想知道我可以用以下键将其转换为Jason文件吗? KeywordsResults

如果我能把结果分开,那就太好了。如果没有,那没关系


Tags: 文件developeretlresultsoraclescorelead文本文件
3条回答
>>> import json
>>> with open('$path_to_file') as f: j = json.load(f)
>>> jk = j[0]['Keywords']
>>> jr = j[0]['Results']
>>> with open('k.txt', 'w') as f: json.dump({'Keywords':jk},f)
>>> with open('r.txt', 'w') as f: json.dump({'Results':jr},f)

不是python方法,但可以在终端上使用^{}

cat file.txt | jq "." > file.json

把他们分开

cat file.txt | jq ".[].Keywords" > keywords.json
cat file.txt | jq ".[].Results" > results.json

(这将适用于数组中的每个条目,如果您只需要一个条目,请添加索引,例如jq ".[0].Keywords

试一试

import json
with open("file.txt", "rb") as f:
    content = json.load(f)
with open("fileJson.txt", "wb") as fout:
    json.dump(content, fout, indent=1)

或访问Text to Json获取答案

相关问题 更多 >