【问题标题】:Changing .json file in python在 python 中更改 .json 文件
【发布时间】:2020-10-08 13:14:10
【问题描述】:

我有以下这样的 .json 文件:

[
  {
    "2004": "0",
    "2005": "0",
    "2006": "0",
    
  },
  {
    "2004": "0",
    "2005": "0",
    "2006": "0",
  },
  {
  
    "2013": "0",
    "2014": "0",
    "2015": "--",
  }
]

如何在python中获取如下的.json文件:

{
 "Countries": [
   {
    "2004": "0",
    "2005": "0",
    "2006": "0"
   },
   {
    "2004": "0",
    "2005": "0",
    "2006": "0"
   },
   {
    "2013": "0",
    "2014": "0",
    "2015": "--"
   }
 ]
}

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    对于您使用文件的情况,请在脚本开头更改为 use_files = True 并设置正确的文件名,而不是 'input.json''output.json'

    Try it online!

    import json
    
    use_files = False
    inp_fname, out_fname = 'input.json', 'output.json'
    
    if not use_files:
        text = """
        [
          {
            "2004": "0",
            "2005": "0",
            "2006": "0"
          },
          {
            "2004": "0",
            "2005": "0",
            "2006": "0"
          },
          {
          
            "2013": "0",
            "2014": "0",
            "2015": "--"
          }
        ]
        """
    
    if use_files:
        with open(inp_fname, 'r', encoding = 'utf-8') as f:
            text = f.read()
    
    obj = json.loads(text)
    obj = {'Countries': obj}
    rtext = json.dumps(obj, indent = 4, ensure_ascii = False)
            
    if use_files:
        with open(out_fname, 'w', encoding = 'utf-8') as f:
            f.write(rtext)
    else:
        print(rtext)
    

    代码输出:

    {
        "Countries": [
            {
                "2004": "0",
                "2005": "0",
                "2006": "0"
            },
            {
                "2004": "0",
                "2005": "0",
                "2006": "0"
            },
            {
                "2013": "0",
                "2014": "0",
                "2015": "--"
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2020-12-20
      • 2013-09-02
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 2016-09-14
      • 2013-04-21
      相关资源
      最近更新 更多