Python program to convert one string to JSON

Python program to convert one string to JSON :

This post will show you how to convert one string to JSON in python. For dealing with JSON, python comes with one inbuilt module called json. This module provides one method called loads() that can be used to convert one string to JSON in python.

For invalid JSON, this will throw one JSONDecodeError.

This method uses the following translation for decoding:

JSON Python
object dict
string str
array list
int int
real float
true True
false False
null None

Example of json.decode() :

Below is the complete example of json.decode() :

import json
given_str = '''
{
    "student": [
        {
            "name": "Alex",
            "age": 12,
            "updated": true,
            "notes": null,
            "marks": 90.0
        },
        {
            "name": "Bob",
            "age": 14,
            "updated": false,
            "notes": null,
            "marks": 80.0
        }
    ]
}
'''

student_json = json.loads(given_str)

print(student_json)

It will print the below output:

{'student': [{'name': 'Alex', 'age': 12, 'updated': True, 'notes': None, 'marks': 90.0}, {'name': 'Bob', 'age': 14, 'updated': False, 'notes': None, 'marks': 80.0}]}

As you can see that the string is decoded based on the translation table we defined above.

Python string to json

Accessing the values of decoded JSON:

Accessing the values from a JSON is easy. We can get one list or any value from that list using the ‘key’. For example:

...
...
...
student_json = json.loads(given_str)

student_list = student_json['student']
first_student_name = student_list[0]['name']

print(student_list)
print(first_student_name)

These two print statements will print:

[{'name': 'Alex', 'age': 12, 'updated': True, 'notes': None, 'marks': 90.0}, {'name': 'Bob', 'age': 14, 'updated': False, 'notes': None, 'marks': 80.0}]
Alex

student_list is a list. We can also iterate through the list using a loop.

for item in student_list:
    print(item['name'])

You might also like: