从 Json 在 Python 中创建具有多个键值的嵌套 Json 结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23255512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating nested Json structure with multiple key values in Python from Json
提问by Learning stats by example
My code is as follows:
我的代码如下:
import json
def reformat(importscompanies):
#print importscompanies
container={}
child=[]
item_dict={}
for name, imports in importscompanies.iteritems():
item_dict['name'] = imports
item_dict['size'] = '500'
child.append(dict(item_dict))
container['name'] = name
container['children'] = child
if __name__ == '__main__':
raw_data = json.load(open('data/bricsinvestorsfirst.json'))
run(raw_data)
def run(raw_data):
raw_data2 = raw_data[0]
the_output = reformat(raw_data2)
My issue is, the code isn't going through the whole file. It's only outputting one entry. Why is this? Am I rewriting something and do I need another dict that appends with every loop?
我的问题是,代码没有遍历整个文件。它只输出一个条目。为什么是这样?我是否在重写一些东西,我是否需要另一个在每个循环中附加的字典?
Also, it seems as though the for loop is going through the iteritems for each dict key. Is there a way to make it pass only once?
此外,似乎 for 循环正在遍历每个 dict 键的迭代项。有没有办法让它只通过一次?
The issue is indeed
问题确实是
raw_data2 = raw_data[0]
I ended up creating an iterator to access the dict values.
我最终创建了一个迭代器来访问 dict 值。
Thanks.
谢谢。
Lastly, I'm hoping my final Json file looks this way, using the data I provided above:
最后,我希望我的最终 Json 文件看起来像这样,使用我上面提供的数据:
{'name': u'name', 'children': [{'name': u'500 Startups', 'size': '500'}, {'name': u'AffinityChina', 'size': '500'}]}
回答by s16h
"It's only outputting one entry" because you only select the first dictionary in the JSON file when you say raw_data2 = raw_data[0]
“它只输出一个条目”因为当你说的时候你只选择了 JSON 文件中的第一个字典 raw_data2 = raw_data[0]
Try something like this as a starting point (I haven't tested/ran it):
尝试这样的事情作为起点(我还没有测试/运行它):
import json
def run():
with open('data/bricsinvestorsfirst.json') as input_file:
raw_data = json.load(input_file)
children = []
for item in raw_data:
children.append({
'name': item['name'],
'size': '500'
})
container = {}
container['name'] = 'name'
container['children'] = children
return json.dumps(container)
if __name__ == '__main__':
print run()
回答by eric chiang
Try this. Though your sample input and output data don't really give many clues as to where the "name" fields should come from. I've assumed you wanted the name of the original item in your list.
尝试这个。尽管您的示例输入和输出数据并没有真正提供很多关于“名称”字段应该来自哪里的线索。我假设您想要列表中原始项目的名称。
original_json = json.load(open('data/bricsinvestorsfirst.json'),'r')
response_json = {}
response_json["name"] = "analytics"
# where your children list will go
children = []
size = 500 # or whatever else you want
# For each item in your original list
for item in original_json:
children.append({"name" : item["name"],
"size" : size})
response_json["children"] = children
print json.dumps(response_json,indent=2)