10

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

str1 = "{'a':'1', 'b':'2'}"
6
  • 2
    That string is JSON. Do you mean how to parse that JSON into a Python dictionary? Commented Oct 24, 2019 at 11:47
  • 1
    Hello and welcome to SO. You may want to read about How to Ask and try doing a minimal searching effort by yourself. Hint: it's in the stdlib. Commented Oct 24, 2019 at 11:52
  • Does this answer your question? Convert JSON string to dict using Python Commented Apr 15, 2020 at 22:34
  • This string is not JSON. It uses single-quotes around the keys and values. Commented Apr 15, 2020 at 23:00
  • str1 = str1.replace("'", '"') then use the solution in the link. Commented Apr 16, 2020 at 0:29

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

-2
import json

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

jsonData = json.loads(str1)

print(jsonData["a"])

Reference : LINK

2 Comments

"ValueError: Expecting property name: line 1 column 2 (char 1)" - better to test your code before posting. Also, the reference documentation is docs.python.org/3/library/json.html
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.