PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » JSON » Converting JSON String to Dictionary Not List

Converting JSON String to Dictionary Not List

Updated on: March 9, 2021 | Python Tags: JSON Python

TweetF  sharein  shareP  Pin

You are here because when you decoded a JSON data and expected JSON data to be a dict type, but it comes out as a list type.

Further reading

  • Solve Python JSON Exercise to practice Python JSON skills

In other words, You want to parse a JSON file and convert the JSON data into a dictionary so you can access JSON using its key-value pairs, but when you parse JSON data, you received a list, not a dictionary. In this article, we will see how to access data in such situations. Before that, first, understand why this happens.

  • It can happen because your JSON is an array with a single object inside, for example, somebody serialized the Python list into JSON. So when you parse it, you get a list object in return. In this case, you need to iterate the list to access data.
  • Also, if somebody serialized Python list(which contains a dictionary) into JSON. When you parse it, you will get a list with a dictionary inside. We will see how to access such data.

We will see both examples. but first, understand the scenario with an example.

import json

sampleList = [125, 23, 85, 445]

# Serialization
print("serialize into JSON and write into a file")
with open("sampleFile.json", "w") as write_file:
    json.dump(sampleList, write_file)
print("Done Writing into a file")

# Deserialization
print("Started Reading JSON data from file")
with open("sampleFile.json", "r") as read_file:
    data = json.load(read_file)
print("Type of deserialized data: ", type(data))

Output:

serialize into JSON and write into a file
Done Writing into a file
Started Reading JSON data from file
Type of deserialized data:  <class 'list'>

As you can see, we received a list from the json.load() method because we serialized only list type object. Now we can access data by iterating it like this. just add the following lines at the end of the above example and execute it.

print("Data is")
for i in data:
    print(i)

Output:

Data is
125
23
85
445

Deserialize a JSON array that contains a dictionary inside

Now, Let’s see the second scenario. Let’s assume somebody serialized Python list(which contains a dictionary) into JSON.  i.e., The list contains a dictionary inside.

In this example, I am serializing the following MarksList into JSON.

StudentDict = {"id": 22, "name": "Emma"}
MarksList = [StudentDict, 78, 56, 85, 67]

You can access the actual dictionary directly by accessing 0th items from the list. Let’s see the example now.

import json

StudentDict = {"id": 22, "name": "Emma"}
MarksList = [StudentDict, 78, 56, 85, 67]

# Serialization
encodedJson = json.dumps(MarksList, indent=4)

# Deserialization

data = json.loads(encodedJson) # or you can read from file using load()
print("Type of deserialized data: ", type(data))

print("JSON Data is")
for i in data:
    if isinstance(i, dict):
        for key, value in i.items():
            print(key, value)
    else:
        print(i)

Output:

Type of deserialized data:  <class 'list'>
JSON Data is
id 22
name Emma
78
56
85
67

Also, you can access limited data directly using a key name using the following code.

studentId = data[0]["id"]
studentName = data[0]["name"]
print(studentId, studentName)

Let’ I know if this doesn’t answer your question in the comment section.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

JSON Python

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

Leave a Comment

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

 Python JSON

  • Python JSON Guide
  • JSON Serialization
  • JSON Parsing
  • JSON Validation
  • PrettyPrint JSON
  • Make Python Class JSON serializable
  • Convert JSON Into Custom Python Object
  • Python JSON Unicode
  • Parse JSON using Python requests
  • Post JSON using Python requests
  • Serialize DateTime into JSON
  • Serialize Python Set into JSON
  • Serialize NumPy array into JSON
  • Parse multiple JSON objects from file
  • Parse Nested JSON
  • Python JSON Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python Regex Python Random Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON
TweetF  sharein  shareP  Pin

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Privacy Policy
  • Cookie Policy
  • Terms Of Use
  • Contact Us
DMCA.com Protection Status

Copyright © 2018-2021 · [pynative.com]

This website uses cookies to ensure you get the best experience on our website.Privacy PolicyGot it!