How can i convert the below string to JSON using python?
str1 = "{'a':'1', 'b':'2'}"
How can i convert the below string to JSON using python?
str1 = "{'a':'1', 'b':'2'}"
The json
library in python
has a function loads
which enables you to convert a string (in JSON format) into a JSON. Following code for your reference:
import json
str1 = '{"a":"1", "b":"2"}'
data = json.loads(str1)
print(data)
Note: You have to use '
for enclosing the string, whereas "
for the objects and its values.
The string in OP's question is not JSON because the keys and values are enclosed by single-quotes. The function ast.literal_eval
can be used to parse this string into a Python dictionary.
import ast
str1 = "{'a':'1', 'b':'2'}"
d = ast.literal_eval(str1)
d["a"] # output is "1"
Other answers like https://stackoverflow.com/a/58540688/5666087 and https://stackoverflow.com/a/58540879/5666087 were able to use the json
library because they changed str1
from "{'a':'1', 'b':'2'}"
to '{"a":"1", "b":"2"}'
. The former is invalid JSON, whereas the latter is valid JSON.
import json
str1 = '{"a":"1", "b":"2"}'
jsonData = json.loads(str1)
print(jsonData["a"])
Reference : LINK