我有一个json文件;我需要从内容中删除id键,这可以用我的代码完成。

现在,我想在新文件中打印json文件的每一行,并使用我在json中归档的名称作为文件名。

我的json文件例如:

{"categories":["Test"],"indications":[{"@class":"=indication.BuildLogIndication","pattern":".*TypeError .*"},{"@class":"model.indication.BuildLogIndication","pattern":".*LoadError .*"}],"modifications":[{"time":{"$date":"2015-10-08T20:01:54.075Z"}},{"user":"user1","time":{"$date":"2015-03-04T18:38:58.123Z"}},{"user":"user2","time":{"$date":"2014-11-13T01:54:13.906Z"}},{"time":{"$date":"2014-09-02T18:48:05.000Z"}}],"lastOccurred":{"$date":"2017-01-25T20:05:17.180Z"}}
{"pattern":".*look for this string.*"}],"modifications":[{"time":{"$date":"2014-09-02T18:52:20.000Z"}}],"lastOccurred":{"$date":"2014-11-04T00:43:32.945Z"},"_removed":{"timestamp":{"$date":"2014-11-13T01:52:44.346Z"},"by":"user3"},"active":false}


删除ID的代码:

import json
import sys
import re
import fileinput

infile = "failure.json"
outfile = "failure1.json"

fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
    for word in line:
        line = re.sub("\"_id.*?},","", line)
    fout.write(line)
    file.write("%d\n" % n)
fin.close()
fout.close()

最佳答案

您的示例输入在每行上显示一个json对象。

因此,我的解决方案读取每一行并将其转换为python dict(使用json.loads()),从dict中删除​​所需的键(如果不存在该键,则使用dict.pop()静默失败)并进行转换将其返回到字符串(使用json.dumps()),然后将其写入新文件。

import json

infile = "failure.json"
outfile = "failure1.json"
key = '_id'

with open(infile) as f_read:
    with open(outfile, 'w') as f_write:
        for line in f_read:
            line = line.strip()
            if len(line) > 0:
                try:
                    elem = json.loads(line)
                    elem.pop(key, None)
                    f_write.write('{}\n'.format(json.dumps(elem)))
                except json.JSONDecodeError:
                    pass




编辑:显然,根据操作员的评论,每个json行都应放入一个单独的新文件中。例如,可以这样做:

import json

infile = "failure.json"
key_to_remove = '_id'

with open(infile) as f_read:
    for line in f_read:
        line = line.strip()
        if len(line) > 0:
            try:
                elem = json.loads(line)
                elem.pop(key_to_remove, None)

                outfile = '{}.json'.format(elem['name'])      # this may raise KeyError
                with open(outfile, 'w') as f_write:
                    f_write.write('{}\n'.format(json.dumps(elem)))
            except json.JSONDecodeError:
                pass

关于python - 使用Python在新的.json文件中打印json的每一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52633468/

10-11 22:20
查看更多