This tutorial help to convert a string into JSON using python. We use JSON to store and exchange data into API. Python has in-built methods to help for string to json like dumps() and eval().
The python getter API receives information in JSON format, We can extract meaningful information we need to convert that data in dictionary form and use it for further operations.
What’s JSON
JSON stands for JavaScript Object Notation. it’s easy for both humans and machines to create and understand.
Simple Example of JSON
{ "firstName": "Adam", "lastName": "Joe", "age": 23 }
JSON serialization
The process of encoding JSON is usually called serialization. The JSON library has a dump()
method for writing data to files and a dumps()
method for writing to a Python string.
JSON deserialization
This is the reciprocal process of decoding data that has been stored or delivered in the JSON standard.
Python JSON package
Python comes with a built-in package called json for encoding and decoding JSON data.
You can import it into your application by adding the below line at the top of your file:
import json
String to JSON
We can convert a string into JSON using dumps()
method.
import json # inititialising json object json_obj = {"firstName": "Adam", "lastName": "Joe", "age": 23} # printing initial json j_string = json.dumps(json_obj) print ("origional json", json_obj) print ("type of obj", type(j_string)) # converting string to json convert_dict = json.loads(j_string) print ("converted dictionary", str(convert_dict))
Output:
origional json {'firstName': 'Adam', 'lastName': 'Joe', 'age': 23} type of obj <class 'str'> converted dictionary {'firstName': 'Adam', 'lastName': 'Joe', 'age': 23} ** Process exited - Return Code: 0 ** Press Enter to exit terminal
String Object to Python Dict
The function eval()
is a built-in function that takes an expression as an input and returns the result of the expression on evaluation.
Let’s convert str object into dict using eval() method.
# inititialising json object json_obj = """{'firstName': 'Adam', 'lastName': 'Joe', "age": 23}""" # printing initial json print ("origional json", json_obj) print ("type of obj", type(json_obj)) # converting string to json convert_dict = eval(json_obj) print ("converted dictionary", str(convert_dict))
we have created a JSON object string and stored it in a variable. next, we converted it into a python dict object using eval() method. the eval method takes JSON string as a parameter.
Output:
origional json {'firstName': 'Adam', 'lastName': 'Joe', "age": 23} type of obj <class 'str'> converted dictionary {'firstName': 'Adam', 'lastName': 'Joe', 'age': 23} ** Process exited - Return Code: 0 ** Press Enter to exit terminal