-1

Currently I'm parsing a string using split and returning the below

{fruit1:"Apple",fruit2:"Orange",fruit3:"Pear"}

I want to convert this string to json using json.loads but I get the below error

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes

How would I go about adding double quotes to this string so I can perform the desired result below

food = '{"fruit1":"Apple","fruit2":"Orange","fruit3":"Pear"}'

print(food['fruit1'])

-----------

Apple
curtcab
  • 73
  • 1
  • 2
  • 11
  • 4
    Why don't you create the string using `json.dumps()` in the first place? – Barmar Nov 01 '21 at 14:46
  • 1
    That isn't JSON input at all. Maybe it's JavaScript? If you created it as JSON you wouldn't have this problem. If you really want to convert other JavaScript into JSON, the best way to do that is with a JavaScript interpreter. – Charles Duffy Nov 01 '21 at 14:46
  • 1
    The easiest way would be to write the string out as proper JSON in the first place. Where is that string coming from? Looks like JS as others have said, but JS provides a function to convert objects to valid json: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify – erik258 Nov 01 '21 at 14:47
  • 1
    You can't reliably add the quotes -- quotes and escape sequences are needed to make the input unambiguous. – Barmar Nov 01 '21 at 14:47

1 Answers1

2

At least in this case, you can treat the string as a jq filter, and use the Python bindings for jq (a third-party package, not in the standard library) to evaluate it to a dict object.

>>> import jq
>>> d = jq.first('{fruit1:"Apple",fruit2:"Orange",fruit3:"Pear"}', None)
>>> d['fruit1']
'Apple'
chepner
  • 497,756
  • 71
  • 530
  • 681