首页 > 解决方案 > 在 python 中更改 .json 文件

问题描述

我有以下 .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": "--"
   }
 ]
}

标签: pythonjsonpandas

解决方案


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

在线尝试!

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": "--"
        }
    ]
}

推荐阅读