【问题标题】:How to modify multiple json files如何修改多个json文件
【发布时间】:2020-09-11 13:14:45
【问题描述】:

我有一个包含 100 个 json 文件的文件夹,我必须在每个文件的开头添加 [,在每个文件的末尾添加 ]

文件结构为:

{
item
}

但是,我需要像这样转换它们:

[{
item
}]

怎么做?

【问题讨论】:

  • json.dump([json.load(infile)], outfile).
  • 使用 GNU sed:sed -i '1s/^/[/; $s/$/]/' file.json

标签: python json


【解决方案1】:

虽然我通常建议对与 JSON 相关的任何内容使用 json.loadjson.dump,但由于您的特定要求,以下脚本就足够了:

import os

os.chdir('path to your directory')

for fp in os.listdir('.'):
    if fp.endswith('.json'):
        f = open(fp, 'r+')
        content = f.read()
        f.seek(0)
        f.truncate()
        f.write('[' + content + ']')
        f.close()

【讨论】:

    【解决方案2】:

    您可以使用 glob 模块来解析所有文件。然后您可以读取内容,然后修改该内容并写回文件

    from glob import glob
    
    for filename in glob('./json/*.json'):
        f = open(filename, 'r')
        contents = f.read()
        f.close()
        new_contents = f"[{contents}]"
        f = open(filename, 'w')
        f.write(new_contents)
        f.close()
    

    【讨论】:

      【解决方案3】:
      import glob
      for fn in glob.glob('/path/*'):
          with open(fn, 'r') as f:
              data = f.read()
          with open(fn, 'w') as f:
              f.write('[' + data + ']')
      

      【讨论】:

        【解决方案4】:

        TL;DR

        # One file
        
        $ jq '.=[.]' test.json | sponge test.json
        
        # Many files
        
        find . -type f -name '*.json' -exec sh -c "jq '.=[.]' "{}" | sponge "{}"" \;
        

        故障

        让我们来一个示例文件

        $ cat test.json 
        
        {
            "hello":"world"
        }
        
        $ jq '.=[.]' test.json 
        

        上面,点(.)代表根节点。所以我将根节点放在括号内。所以我们得到:

        [
          {
            "hello": "world"
          }
        ]
        

        现在我们需要获取输出并将其放回文件中

        $ jq '.=[.]' test.json | sponge test.json
        $ cat test.json
        
        [
          {
            "hello": "world"
          }
        ]
        

        接下来,让我们找到我们想要这样做的所有 json 文件

        $ find . -type f -name '*.json' 
        ./test.json
        

        我们可以遍历 find 命令的每一行并将其分类如下:

        $ find . -type f -name '*.json' -exec cat {}\;
        {
            "hello":"world"
        }
        

        或者我们可以编写我们需要的 jq 命令。文件名传递给-exec\; 之间的花括号

        $ find . -type f -name '*.json' -exec sh -c "jq '.=[.]' "{}" | sponge "{}"" \;
        

        感谢zeppelin

        【讨论】:

          猜你喜欢
          • 2016-10-11
          • 1970-01-01
          • 1970-01-01
          • 2017-11-09
          • 2019-05-08
          • 2019-12-12
          • 1970-01-01
          • 1970-01-01
          • 2021-06-12
          相关资源
          最近更新 更多