I want to convert a dictionary like this:
{
"name": "Paul",
"age": "20",
"gender": "male"
}
to this :
{
name: "Paul",
age: "20",
gender: "male"
}
Basically the same as a JSON, but the object properties cannot be wrapped around quotes. Is it possible to do that in Python?
asked Jun 28, 2022 at 5:28
João Pedro
1,0084 gold badges19 silver badges40 bronze badges
2 Answers 2
In Python:
import json
send_to_js = json.dumps({
"name": "Paul",
"age": "20",
"gender": "male"
})
Then in JavaScript:
JSON.parse(send_to_js)
// result is {name: 'Paul', age: '20', gender: 'male'}
In the end I did it using regex:
def saveFile(dictionary, fileName):
jsonStr = json.dumps(dictionary, indent=4, ensure_ascii=False);
removeQuotes = re.sub("\"([^\"]+)\":", r"1円:", jsonStr);
fileNameCleaned = fileName.split(" ")[0]
with open(fileNameCleaned + ".ts", "w",encoding='utf_8') as outfile:
outfile.write("export const " + fileNameCleaned + " = " + removeQuotes + ";")
answered Jun 28, 2022 at 6:20
João Pedro
1,0084 gold badges19 silver badges40 bronze badges
Comments
lang-py
pythonhas dictionaries that are almost the same as javascript objectJSON. and python will manipulate the first one same as the js object. and the conversion can only be achieved by manipulatingstrordictobject i.e. by performing string operations. By the way, where do you want to use the second one? If it is for javascript, then no need to convert.