-1

I'm trying to parse the test_string to JSON but failing, just continues as string after json.dumps, see result below. How can I get the expected output? The test_string is pulled from a text object and that's how it's quoted.

test_string = "{'fruit': ['Yes'], 'vegetables': ['carrot']}"

# output
json.dumps(test)
'"{\'fruit\': [\'Yes\'], \'vegetables\': [\'carrot\']}"'

# expected output
{'fruit': ['Yes'], 'vegetables': ['carrot']}
5
  • 2
    Do you not want to be using json.loads? json.dumps is for creating a string from a python object. Though I don't thing your test_string will parse as JSON wants double quotes.
    – Alex
    Sep 2, 2021 at 19:20
  • You can use eval() function to create a dict from String. Then you can use json.dumps()
    – d-xa
    Sep 2, 2021 at 19:28
  • @Alex json.loads gives a decoding error. ast.literal_eval worked
    – Aks
    Sep 8, 2021 at 16:07
  • @Aks JSON syntax is not Python syntax. JSON requires double quotes for its strings.
    – Alex
    Sep 8, 2021 at 16:52
  • @Alex it's from a text object, that's how it is in the document that is getting parsed, which is why json.loads fails
    – Aks
    Sep 9, 2021 at 17:09

2 Answers 2

2

use ast and json

import ast
import json
data = ast.literal_eval("{'fruit': ['Yes'], 'vegetables': ['carrot']}")
print(json.dumps(data))

output

{"fruit": ["Yes"], "vegetables": ["carrot"]}
1

json.loads() should do the trick

test_string = "{'fruit': ['Yes'], 'vegetables': ['carrot']}"
new_test_string = json.loads(test_string)
1
  • json.loads gives a JSONDecodeError. ast.literal_eval works
    – Aks
    Sep 8, 2021 at 16:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.