0

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

Nathon
  • 165
  • 1
  • 4
  • 13
  • I don't understand the problem. `{"fruite":"aapple", "code":"1xyz"}` is a python literal that is converted to a dictionary and assigned to `ss` when the program is executed. Its not JSON at all, its already python, so `json.load` which converts strings to python won't work. If you wanted to create a json string you could `json.dumps(ss)` but I don't see any reason for `json.load` to be in the code. What is your goal? To make a python `dict`? You already did that. – tdelaney Jul 28 '20 at 05:47

1 Answers1

2

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
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Thanks @Serge Ballesta, It works. I am able to load the js string without converting into single quotes. – Nathon Jul 28 '20 at 06:04
  • @Nathon: never try to convert *by hand* where the conversion exists in a standard module. Their code has been extensively tested and is robust to corner cases, while yours may not. – Serge Ballesta Jul 28 '20 at 06:11