【问题标题】:Print each line of json in new .json file using Python使用 Python 在新的 .json 文件中打印每一行 json
【发布时间】:2018-10-03 18:24:15
【问题描述】:

我有一个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 包,但是你没有使用它。应该的,太好了从文件中获取字符串,然后使用json.loads() 将字符串加载到 json 对象中。从那里,您可以使用 for key in json_object 获取 json 对象的每个元素。
  • @mindfolded 你能把它写成一个解决方案吗.. 非常合适.. 我也是 Python 新手.. 非常感谢
  • @jantamm 已经写成解决方案了。

标签: python json loops


【解决方案1】:

对于删除,您可以使用以下内容:

import json
import sys
import re
import fileinput

with open('failure.json') as data_file:
    data = json.load(data_file)
    del data['_id']


with open('failure2.json', 'w') as data_file:
    data = json.dump(data, data_file)

为了创建具有 id 值的文件,只需解析 data 对象和 id 节点的值

【讨论】:

    【解决方案2】:

    您的示例输入在每一行显示一个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
    

    编辑:根据 OPs cmets 的说法,显然每个 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
    

    【讨论】:

    • 谢谢,但我想在新文件中打印 json 文件的每一行,并使用我的 json 中归档的名称作为文件名。
    • json数据中哪个key包含新文件名?
    • 名称 >> "名称":"Ruby"
    • 谢谢,快速提问,我们如何在生成文件之前检查名称字段中的特殊字符(如“/”)并用“_”替换它们?提前致谢
    • @JanTamm 你可以做elem['name'].replace('/', '_') 或类似的事情
    【解决方案3】:

    您已导入 json 包,但您没有使用它。你应该,这很棒。

    从文件中获取字符串,然后使用json.loads() 将字符串加载到 json 对象中。从那里,您可以使用 for key in json_object 获取 json 对象的每个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2016-01-22
      • 2017-03-13
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多