我正在将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
语法有什么问题吗?
答案 0 :(得分:1)
编辑:
将您自己的字典附加到列表然后将整个内容转储到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)
答案 1 :(得分:1)
这是因为import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
第一个参数json.dump()
是您希望序列化为JSON格式的文件的对象(类似于f)。
您正在for循环中传递obj
。因此,不是创建包含多个对象的单个JSON数组,而是创建包含单个对象的多个JSON数组。 [{"Key": val2, "Value": val1}]
应该发生在for循环之外,并被赋予构造好的对象列表。
尝试一下:
json.dump()