首页 > 解决方案 > json文件写入格式问题

问题描述

我正在将 python 的输出写入 json 文件。

我尝试的是:

with open(r"c:\csv\file.json", "w") as f:
    ec2 = boto3.resource('ec2')
    #ids = inst_id
    for instance in ec2.instances.filter(InstanceIds=[inst_id]):
       #print (instance.tags)
       for tag in instance.tags:
           val1 = (tag['Value'])
           val2 = (tag['Key'])
           json.dump([{"Key": val2, "Value": val1}], f, indent=4, separators=(',', ': '))

预期输出:

[
  {
    "Key": "Name",
    "Value": "node1"
  },
  {
    "Key": "owner",
    "Value": "jhonson"
  },
  {
    "Key": "managed",
    "Value": "yes"
  }
]

我得到的是,每对都会有Invalid Output: , missing after each key额外的:[]

[
    {
        "Key": "Name",
        "Value": "node1"
    }
][
    {
        "Key": "owner",
        "Value": "jhonson"
    }
][
    {
        "Key": "managed",
        "Value": "yes"
    }
]

如果我通常只将变量打印到控制台,则输出如下:

Name,node1
owner,jhonson
managed,yes

有人可以建议我的dump语法有什么问题吗?

标签: pythonjsonformat

解决方案


这是因为json.dump()第一个参数obj是您希望作为 JSON 格式流序列化到类文件对象(在您的情况下为 f )的对象。您[{"Key": val2, "Value": val1}]在 for 循环中传递。因此,您不是创建多个对象的单个 JSON 数组,而是创建多个单个对象的 JSON 数组。应该发生在json.dump()for 循环之外并被赋予一个构造的对象列表。

尝试这个:

ec2_tags =[]
ec2 = boto3.resource('ec2')
for instance in ec2.instances.filter(InstanceIds=[inst_id]):
    for tag in instance.tags:       
        val1 = (tag['Value'])
        val2 = (tag['Key'])
        ec2_tags.append({"Key": val2, "Value": val1})

with open(r"c:\csv\file.json", "w") as f:
    json.dump(ec2_tags, f, indent=4, separators=(',', ': '))

推荐阅读