GG24
GG24

Reputation: 303

How to skip fields in a Json file with Python

I'm trying to read a Json file to transform it into csv I looked on some stackoverflow questions and it helped me but I still have a little problem. There are fields that don't interest me and I don't know how to say to my script to skip these fields.

Here is my code :

import csv
import json

x = """{
"year": "2008",
"title": "Movies",
"items": [

{
"title": "The dark knight",
"description": "A batman story"
},

{
"title": "The Mummy: Tomb of the Dragon Emperor",
"description": "A mummy story"

},


{
"title": "Ironman",
"description": "An Avengers story"

}


]
}"""


x = json.loads(x)


for key, value in x.items():
    print(key, value)

Of course I chose a very sample and short text to illustrate my example.

When I run that script I get that :

(u'items', [{u'description': u'A batman story', u'title': u'The dark knight'}, {u'description': u'A mummy story', u'title': u'The Mummy: Tomb of the Dragon Emperor'}, {u'description': u'An Avengers story', u'title': u'Ironman'}]) (u'title', u'Movies') (u'year', u'2008')

And I would like to know how to display only the item's fields and to skip the fields "year" and "title" at the beggining.

So, I would like to get the following output :

[{u'description': u'A batman story', u'title': u'The dark knight'}, {u'description': u'A mummy story', u'title': u'The Mummy: Tomb of the Dragon Emperor'}, {u'description': u'An Avengers story', u'title': u'Ironman'}])

I need to access only to these fields to write them in a csv file after. So do you have an idea how I could do that ?

Thank you very much in advance :)

Upvotes: 1

Views: 1066

Answers (2)

Kevin Kamonseki
Kevin Kamonseki

Reputation: 141

You could do something like this instead:

x = json.loads(x)['items']

for item in x:
    print item['description']
    print item['title']

Upvotes: 1

Elvis D'Souza
Elvis D'Souza

Reputation: 2313

json.loads parses JSON into a dictionary.

You can access the "items" key directly:

print(x["items"])

Upvotes: 3

Related Questions