简体   繁体   English

json 文件写入格式问题

[英]Issue with json file writing format

I am writing output from python to json file.我正在将 output 从 python 写入 json 文件。

What I tried is:我尝试的是:

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=(',', ': '))

Expected output:预期 output:

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

What I get is Invalid Output: , missing after each key , extra [] s are coming for each pair:我得到的是Invalid Output: , missing after each key每对都会有额外的[]

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

If I normally print just variables to console below is output:如果我通常只将变量打印到控制台下面是 output:

Name,node1
owner,jhonson
managed,yes

Can some one suggest what wrong with my dump syntax?有人可以建议我的dump语法有什么问题吗?

EDIT :编辑

It might be easier to append your individual dicts to a list and then dump the whole thing to JSON:将您的个人字典 append 到列表中,然后将整个内容转储到 JSON 可能更容易:

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

with open("data_file.json", "w") as write_file:
    json.dump(data, write_file, indent=4)

It is because json.dump() first parameter obj is the object you wish to serialize as a JSON formatted stream to the file-like object ( f in your case ). It is because json.dump() first parameter obj is the object you wish to serialize as a JSON formatted stream to the file-like object ( f in your case ). You are passing [{"Key": val2, "Value": val1}] within a for loop.您在 for 循环中传递[{"Key": val2, "Value": val1}] So instead of creating a single JSON array of many objects, you are creating many JSON arrays of single objects.因此,不是创建多个对象的单个 JSON 数组,而是创建单个对象的多个 JSON arrays。 the json.dump() should happen outside the for loop and be given a constructed list of objects. json.dump()应该发生在 for 循环之外,并得到一个构造的对象列表。

Try this:尝试这个:

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=(',', ': '))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM