Creating a nested Json structure with multiple key values ​​in Python from Json

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 problem is that the code does not go through the whole file. It displays only one entry. Why is this? Am I rewriting something and need another announcer that joins each cycle?

Also, it seems that the for loop goes through iterations for each dict key. Is there a way to do this only once?

Problem really

 raw_data2 = raw_data[0]

I ended up creating an iterator to access dict values.

Thank.

Finally, I hope that my last Json file will look like this using the above data:

{'name': u'name', 'children': [{'name': u'500 Startups', 'size': '500'}, {'name': u'AffinityChina', 'size': '500'}]}
+4
source share
2

. , "". , .

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)
+6

" ", JSON, raw_data2 = raw_data[0]

- ( / ):

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()
+1

Source: https://habr.com/ru/post/1537787/


All Articles