Nathon
Nathon

Reputation: 165

How to pass single quotes to json string in python?

How do we convert this below json string into sinle quote in python. Below is my requirement scenario

test.py

import json

import sys

ss = {"fruite":"aapple", "code":"1xyz"}

Tried below commented different ways

#frmt = ("'{}'".format(ss))    ---->Everything is converted to single quotes, 
 
#ss2 = ("'"+ss+"'") not working

jsonld = json.loads(ss)

when i try this json loads its getting json decode error

If i give manually

ss = '{"fruite":"aapple", "code":"1xyz"}' 

working json.loads , its didn't get any issue.

Expecting:

Here how do i pass single quotes to my above json string without changing inside double quotes.

Can you please suggest this

Upvotes: 0

Views: 259

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149155

The json module provides functions to build a json string from a Python object:

ss = {"fruite":"aapple", "code":"1xyz"}
js = json.dumps(ss)
print(js)

Correctly prints:

{"fruite":"aapple", "code":"1xyz"}

But js is now a string and not a dictionary so you can load it:

jsonld = json.loads(js)
print(jsonld == ss)

prints

True

Upvotes: 2

Related Questions