Extract part of data from JSON file with python [duplicate]

孤街浪徒 提交于 2019-11-28 19:58:28

Your code creates new dictionary object for each object with:

my_dict={}

Moreover, it overwrites the previous contents of the variable. Old dictionary in m_dict is deleted from memory.

Try to create a list before your for loop and store the result there.

result = []
for item in json_decode:
    my_dict={}
    my_dict['title']=item.get('labels').get('en').get('value')
    my_dict['description']=item.get('descriptions').get('en').get('value')
    my_dict['id']=item.get('id')
    print my_dict
    result.append(my_dict)

Finally, write the result to the output:

back_json=json.dumps(result, output_file)

Printing the dictionary object aims to help the developer by showing the type of the data. In u'Diego Vel\xe1zquez', u at the start indicates a Unicode object (string). When object using is printed, it is decoded according to current language settings in your OS.

When you do this:

for item in json_decode:

You are looping through each line in the file.

Every time through the loop you are overriding the my_dict variable, which is why you get only one line in your output.

Once you load in the file, you can simply print out the json_decode variable to do what you want.

https://docs.python.org/3.3/library/json.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!