7

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?

The issue is indeed

 raw_data2 = raw_data[0]

I ended up creating an iterator to access the dict values.

Thanks.

Lastly, I'm hoping my final Json file looks this way, using the data I provided above:

{'name': u'name', 'children': [{'name': u'500 Startups', 'size': '500'}, {'name': u'AffinityChina', 'size': '500'}]}
Union find
  • 7,759
  • 13
  • 60
  • 111
  • 1
    Two questions. 1) What are you returning from your `reformat` function? 2) In your desired JSON object, what does 'size' correspond to? – eric chiang Apr 23 '14 at 21:52
  • Could you edit your question to show exactly how you want your final JSON to look like? Use the first 2 elements in the sample list you have provided perhaps. – s16h Apr 23 '14 at 21:54
  • @s16h I've added the examples above. – Union find Apr 23 '14 at 21:54
  • @ericchiang 1) reformat should return the final container (maybe I need one more for an append?) In other words, the properly formatted Json. 2) Size has no corresponding value but is a set numeral. – Union find Apr 23 '14 at 21:56

2 Answers2

12

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)
eric chiang
  • 2,575
  • 2
  • 20
  • 23
  • This needs to loop through a lot more items, so that won't work. Also "name" is derived from an original object and so it also needs to be looped. But thank you that is helpful. – Union find Apr 23 '14 at 22:05
  • 1
    @SamP. What do you mean by needs to loop through a lot more items? A loop will loop through as many items as your list has – eric chiang Apr 23 '14 at 22:06
  • I mean, you've assigned the parent node the name "analytics". That needs to be set variably based on the Json file. So it needs to be looped as my code does. – Union find Apr 23 '14 at 22:08
3

"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]

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()
s16h
  • 4,647
  • 1
  • 21
  • 33
  • I did that because the json.load is coming in as a list, so I thought that would convert to a dict (which it does) while keeping all the data. How is best to circumvent this issue? – Union find Apr 23 '14 at 21:46
  • Could you edit your question to show exactly how you want your final JSON look like? Use the first 2 elements in the sample list you have provided perhaps. – s16h Apr 23 '14 at 21:51
  • `json.load` returns a list in this case because your file has a list of ditionaries. When you say `raw_data2 = raw_data[0]` then you are having `raw_data2` point to only the first element of the `raw_data` list. It wouldn't keep all the data, only the first element. – s16h Apr 23 '14 at 21:57
  • OK I suspected that might be an issue. Do you recommend a fix? I posted the issue here and I got the fix I used. http://stackoverflow.com/questions/23230669/accessing-information-inside-a-list-that-is-formatted-like-a-dictionary-python – Union find Apr 23 '14 at 21:59