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: May 14, 2021 | 1 Comment

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.

Filed Under: Python, Python JSON

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:

Python Python JSON

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

Comments

  1. MA says

    October 1, 2021 at 1:17 am

    Hi, I have a data format like this: .json file

    {"_id":{"$od":"5f12"},"ready":true,"createdon":{"$date":1609687444800},"lastLogin":{"$date":1858},"position":"consumer","signUp":"Email","state":"WI"}
    {"_id":{"$od":"5f12"},"ready":true,"createdon":{"$date":1609687444800},"lastLogin":{"$date":1858},"position":"consumer","signUp":"Email","state":"WI"}

    I used this code in python to try to use the data for analysis.

    import json
    
    with open("users.json", "r") as f:
        json_str = f.read()
        json_value = json.loads(json_str)
    
    print(type(json_value))

    However, I ran into this error:

    Traceback (most recent call last):
      File "json_to_sqlite.py", line 5, in 
        json_value = json.loads(json_str)
      File "/Users/malaba/opt/anaconda3/lib/python3.8/json/__init__.py", line 357, in loads
        return _default_decoder.decode(s)
      File "/Users/malaba/opt/anaconda3/lib/python3.8/json/decoder.py", line 340, in decode
        raise JSONDecodeError("Extra data", s, end)
    json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 186)

    I was told that I have to convert this data from a dictionary to a list. I couldn’t figure out that part. Please help.

    Reply

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 entire code </pre>

Posted In

Python Python JSON
TweetF  sharein  shareP  Pin

  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 File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

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
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com