-1

I want to parse a string of JSON back into a JSON. the string has some boolean values.

Example input:

str_json = "{'name': 'bob', 'id': '11111', 'happy': True, 'sad': False}"

Example output:

d = {"name": "bob", "id": "11111", "happy": "True", "sad": "False"}

I've tried this:

p = re.compile('(?<!\\\\)\'')
str_json = p.sub('\"', str_json)
d = json.loads(str_json)

and got this exception:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 91 (char 90)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • `True` and `False` in `str_json` must be lowercase; in yr desired output `"True"` and `"False"` are strings that will both be interpreted as `true` (`bool("False") --> True`). Where did the initial string come from? – fusion3k Mar 04 '23 at 10:37
  • It’s nowhere near JSON to begin with, it’s a Python literal. – deceze Mar 04 '23 at 10:40

1 Answers1

0

You can try:

import ast
str_json = "{'name': 'bob', 'id': '11111', 'happy': True, 'sad': False}"

j=ast.literal_eval(str_json)

print(j)
#{'name': 'bob', 'id': '11111', 'happy': True, 'sad': False}

Link to document :https://docs.python.org/3/library/ast.html#ast.literal_eval

ast.literal_eval is used for evaluating string.


Finally convert the boolean values to string:

new={k:str(v) for k,v in j.items()}
#output
{'name': 'bob', 'id': '11111', 'happy': 'True', 'sad': 'False'}
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44