我有下面的文件,这是json转储的结果。
"fdd6a102-359c-4527-8469-4ef01a9c0076": "[\n {\n \"resource_status\": \"CREATE_COMPLETE\", \n \"resource_name\": \"i4_instance_internal_port\", \n \"resource_type\": \"OS::Neutron::Port\", \n \"physical_resource_id\": \"5db1d412-9a43-45c7-b72d-0dbe4eb16497\", \n \"updated_time\": \"2017-07-14T09:00:44\"\n }, \n {\n \"resource_status\": \"CREATE_COMPLETE\", \n \"resource_name\": \"i3_instance\", \n \"resource_type\": \"OS::Nova::Server\", \n \"physical_resource_id\": \"50375d90-5b57-412e-afe3-fdddefbd2f41\", \n \"updated_time\": \"2017-07-14T09:00:44\"\n }, \n {\n \"resource_status\": \"CREATE_COMPLETE\", \n \"resource_name\": \"i3_v1_instance_volume\", \n \"resource_type\": \"OS::Cinder::Volume\", \n \"physical_resource_id\": \"6750dc3d-e682-4a0c-a177-83a7252822fb\", \n \"updated_time\": \"2017-07-14T09:00:44\"\n }\n]\n"
我认为这个文件搞砸了。它的格式不正确。我研究了如何在json中转储
def pp_another_json(myDict):
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(myDict,
indent=4, sort_keys=True,
ensure_ascii=False)
outfile.write(to_unicode(str_))
class getstackList():
def getStackID(self):
stacks = get_objects('stacks')
myDict = {}
for stack in stacks:
try:
myDict[stack.id] = subprocess.check_output(["openstack", "stack", "resource", "list", stack.id, "-f", "json"])
pp_another_json(myDict)
except subprocess.CalledProcessError as e:
print("Error")
openstack堆栈资源列表-f json的输出格式为
[
{
"resource_status": "CREATE_COMPLETE",
"resource_name": "i4_instance_internal_port",
"resource_type": "OS::Neutron::Port",
"physical_resource_id": "5db1d412-9a43-45c7-b72d-0dbe4eb16497",
"updated_time": "2017-07-14T09:00:44"
},
{
"resource_status": "CREATE_COMPLETE",
"resource_name": "i3_instance",
"resource_type": "OS::Nova::Server",
"physical_resource_id": "50375d90-5b57-412e-afe3-fdddefbd2f41",
"updated_time": "2017-07-14T09:00:44"
},
]
现在我的问题
如果有人能解释我的json文件会很有帮助。如果没有,请指导我帮助我理解嵌套词典的链接
已编辑:要获取我在下面执行的值并给出了ValueError:要解压的值太多
with open('data.json') as data_file:
data_loaded = json.load(data_file)
for key, value in data_loaded:
print(data_loaded[key][0]['resource_status'])
答案 0 :(得分:0)
您的JSON转储可以在python中被视为一个简单的字典。因此,对于您的第一部分,您可以使用以下内容:
import json
#Assuming 'mydict' contains the json dump
with open('out.json', 'w') as outfile:
json.dump(mydict, outfile)
现在进入第二部分,假设您的示例中的第一个元素(fdd6a102-359c-4527-8469-4ef01a9c0076“)需要访问列表中第一个元素的”resource-status“键,只需要使用以下内容:
myjson["fdd6a102-359c-4527-8469-4ef01a9c0076"][0]['resource-status']
更多信息可以是found here。
在最后一部分中,您可以查看this answer on nested JSON。