python - 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
语法有什么问题吗?
解决方案
这是因为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=(',', ': '))
推荐阅读
- javascript - 如何从 VueJs 中的不同字段上传多个图像?
- python - 乌班图;Python3 - Textract 安装 - Ebooklib 和 pocketsphinx 的编解码器错误
- python - 安装 pyrcc4 时有什么指导吗?
- scala - Twitter 未来与猫箭
- python - 重新定义子类的 __init__ 以采用不同的参数
- c# - 迭代进行 BFS 或 DFS 遍历时,如何获取有关当前访问级别的信息?
- file - 如何在 Delphi 中追加到文本文件?
- python - 在 numpy 数组中运行 max-min 的窗口。
- php - 联系表格 7 数据库 get_current_user_id 显示 0
- laravel - 终端字母全白,无法使用 la el 命令