1

I'm having trouble with getting a certain key from a json file in python. I really don't know where to start since I never used json with python before.

[
  {
    "author": "Chinua Achebe",
    "country": "Nigeria",
    "imageLink": "images/things-fall-apart.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    "pages": 209,
    "title": "Things Fall Apart",
    "year": 1958
  },
  {
    "author": "Hans Christian Andersen",
    "country": "Denmark",
    "imageLink": "images/fairy-tales.jpg",
    "language": "Danish",
    "link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
    "pages": 784,
    "title": "Fairy tales",
    "year": 1836
  }
]

this is a few lines from the json file as an example.

import json
f = open('**\\booksset1.json')
data = json.load(f)

This part loads the json file, but how would I go ahead to get for example one title from the entire file.

1
  • 1
    Your data is a list of dicts, akin to what you have in the JSON. You can get the first title like how you would if it were a normal list-of-dicts: data[0]['title'] Commented Apr 23, 2019 at 12:50

7 Answers 7

1
data = [
  {
    "author": "Chinua Achebe",
    "country": "Nigeria",
    "imageLink": "images/things-fall-apart.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    "pages": 209,
    "title": "Things Fall Apart",
    "year": 1958
  },
  {
    "author": "Hans Christian Andersen",
    "country": "Denmark",
    "imageLink": "images/fairy-tales.jpg",
    "language": "Danish",
    "link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
    "pages": 784,
    "title": "Fairy tales",
    "year": 1836
  }
]


# Get all authors in a list (might want to convert to set to remove duplicates)     
authors = [d["author"] for d in data] 
print (authors) 

# Find all books by author 'Chinua Achebe'
for book in data:
    if book['author'] == 'Chinua Achebe':
        print (book)


# Find all books later than year 1950         
for book in data:
    if book['year'] > 1950:
        print (book['title'], book['year'])
Sign up to request clarification or add additional context in comments.

Comments

1

Use for loop to access the keys and values. For example

import json
f = open('**\\booksset1.json')
data = json.load(f)

Print First item title: 

print data[0]['title']
To iterate all the of the author details
for d in data:
   print d['author]
   print d['title']

Comments

1

You can use the .get function to get the key's value from the list of dictionary as follows:

data = [
  {
    "author": "Chinua Achebe",
    "country": "Nigeria",
    "imageLink": "images/things-fall-apart.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    "pages": 209,
    "title": "Things Fall Apart",
    "year": 1958
  },
  {
    "author": "Hans Christian Andersen",
    "country": "Denmark",
    "imageLink": "images/fairy-tales.jpg",
    "language": "Danish",
    "link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
    "pages": 784,
    "title": "Fairy tales",
    "year": 1836
  }
]

titles = [item.get("title", "") for item in data]

Outputting:

['Things Fall Apart', 'Fairy tales']

Comments

0

json.load has converted from text string representation into (in this case) a list of dicts. So to access, say, the year of the second one (Fairy tales), use

print( data[1]['year'] ) # should output 1836

You can do all the usual python things, for example iterate over all the dicts in the list:

for d in data:
    author, title, date = d['author'], d['title'], d['year']
    print( f'{author} wrote "{title}" in {year}') 

Comments

0

If you're still having trouble, try using ReadSettings.

from readsettings import ReadSettings # Import readsettings library
f = ReadSettings("file.json") # Load the JSON file
print(f[0]["author"]) # Print the value of "author" from the first dictionary in the list

Here are some other tricks you can do:

f[0]["author"] = "Foo Man" # Set the value
f.json() # Get object from the JSON file

You can find more information here.

Comments

0

This will give you a basic understanding of how to work with JSON in python.

import json
f = open('booksset1.json')
data = json.load(f)
# for single 
print("Aurthor name :",data[0]['author'])
print("Country name :",data[0]['country'])
print()
# for multiple you should use loop
for i in data:
    print(i['title'])

Comments

0

If you prefer using this data in a pandas DataFrame, and since your data behaves like a list of dictionaries, you could try:

import pandas as pd

df = pd.DataFrame.from_dict(data)

df

                    author  country  ...               title  year
0            Chinua Achebe  Nigeria  ...   Things Fall Apart  1958
1  Hans Christian Andersen  Denmark  ...         Fairy tales  1836

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.