Home > Back-end >  Create json with multiple entries in python
Create json with multiple entries in python

Time:10-19

How can I generate the json below in python? I have tried with a dictionary but the first book was constantly overwritten.

{
    "book":[
        {
            "category":"reference",
            "author":"Nigel Rees"
        },
        {
            "category":"fiction",
            "author":"Evelyn Waugh"
        },
        {
            "category":"fiction",
            "author":"J. R. R. Tolkien"
        }
    ]
}

CodePudding user response:

Try this:

import json 

text = """{
    "book":[
        {
            "category":"reference",
            "author":"Nigel Rees"
        },
        {
            "category":"fiction",
            "author":"Evelyn Waugh"
        },
        {
            "category":"fiction",
            "author":"J. R. R. Tolkien"
        }
    ]
}"""    

# parse your text:
results = json.loads(text)
  
# print your results as dictionary:
print(results)

It will get your the output as follows:

{'book': [{'category': 'reference', 'author': 'Nigel Rees'}, {'category': 'fiction', 'author': 'Evelyn Waugh'}, {'category': 'fiction', 'author': 'J. R. R. Tolkien'}]}

CodePudding user response:

In python a dictionary is already valid json.

$cat /tmp/3824
#!/usr/bin/env python
import json

x = {
    "book":[
        {
            "category":"reference",
            "author":"Nigel Rees"
        },
        {
            "category":"fiction",
            "author":"Evelyn Waugh"
        },
        {
            "category":"fiction",
            "author":"J. R. R. Tolkien"
        }
    ]
}
print(json.dumps(x, indent=3))

So if you execute it.

$/tmp/3824
{
   "book": [
      {
         "category": "reference",
         "author": "Nigel Rees"
      },
      {
         "category": "fiction",
         "author": "Evelyn Waugh"
      },
      {
         "category": "fiction",
         "author": "J. R. R. Tolkien"
      }
   ]
}
  • Related