-1

How can i convert the below string to JSON using python?

str1 = "{'a':'1', 'b':'2'}"
jkr
  • 17,119
  • 2
  • 42
  • 68
  • 1
    That string _is_ JSON. Do you mean how to parse that JSON into a Python dictionary? – Amadan Oct 24 '19 at 11:47
  • 1
    Hello and welcome to SO. You may want to read about [ask] and try doing a minimal searching effort by yourself. Hint: it's [in the stdlib](https://docs.python.org/3/library/index.html). – bruno desthuilliers Oct 24 '19 at 11:52
  • Does this answer your question? [Convert JSON string to dict using Python](https://stackoverflow.com/questions/4528099/convert-json-string-to-dict-using-python) – Trenton McKinney Apr 15 '20 at 22:34
  • This string is not JSON. It uses single-quotes around the keys and values. – jkr Apr 15 '20 at 23:00
  • `str1 = str1.replace("'", '"')` then use the solution in the link. – Trenton McKinney Apr 16 '20 at 00:29
  • That would work for this simple string, there could be other characters that would make this non-JSON, like a trailing comma. Better to use `ast.literal_eval` to convert the string to a dict. – jkr Apr 17 '20 at 21:55

3 Answers3

0

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
Rahul Soni
  • 153
  • 3
  • 18
0

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.

jkr
  • 17,119
  • 2
  • 42
  • 68
-2
import json

str1 = '{"a":"1", "b":"2"}'

jsonData = json.loads(str1)

print(jsonData["a"])

Reference : LINK

tyb9900
  • 214
  • 2
  • 11
  • "ValueError: Expecting property name: line 1 column 2 (char 1)" - better to test your code before posting. Also, the reference documentation is https://docs.python.org/3/library/json.html – bruno desthuilliers Oct 24 '19 at 11:59
  • 1
    Hi @tyb9900! You had an good effort to contribute the answer. But, the string for JSON should be enclosed in `'` and not in `"`. Hope, that will help you improve your answer. – Rahul Soni Oct 24 '19 at 12:00