简体   繁体   English

如何从嵌套字典中提取键值对并在json中输出

[英]How to extract a key value pair from a nested dictionary and output it in json

I am extracting part of a dictionary with 我正在提取字典的一部分

with open(output_filename, "w") as outfile:
    json.dump(data['metadata'], outfile)

So that I get the value of 'metadata' and none of the key value pairs before. 这样我就得到了“元数据”的值,之前没有任何键值对。 How do I modify it so I also get the key itself ('metadata') to appear in the output before the value? 如何修改它,这样我也可以使密钥本身(“元数据”)出现在值之前的输出中? I tried this 我试过了

for key in my_dict.keys():
   if key is "metadata":
       val = my_dict[key]

and then using json.dump(val, outfile) but that created an error global name val is not defined (I defined it as a global variable earlier to try to fix an earlier error message.) I can't use just "data" itself because there is a key value pair in data that I want to exclude. 然后使用json.dump(val, outfile)global name val is not defined创建global name val is not defined的错误(我更早地将其定义为全局变量以尝试修复更早的错误消息。)我不能仅使用“数据”本身,因为我要排除的数据中有一个键值对。

with open(output_filename, "w") as outfile:
    json.dump({'metadata': data['metadata']} , outfile)

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

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