1

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?

João Pedro
  • 794
  • 2
  • 12
  • 28
  • you need to use javascript to convert a string dictionary to json object, (not a js guy) – sahasrara62 Jun 28 '22 at 05:30
  • 1
    What do you mean by "cannot"? The quotes are optional in JS, so that input is perfectly valid JS. – wjandrea Jun 28 '22 at 05:31
  • Does this answer your question? [Convert Python dictionary to JSON array](https://stackoverflow.com/questions/14661051/convert-python-dictionary-to-json-array) – jonsca Jun 28 '22 at 05:37
  • `python` has dictionaries that are almost the same as javascript object `JSON`. and python will manipulate the first one same as the js object. and the conversion can only be achieved by manipulating `str` or `dict` object 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. – Muhammad Khuzaima Umair Jun 28 '22 at 06:08
  • 1
    Thanks, for the help. I didn't know properties with quotes were valid JS object keys. However in our codebase that's not the standard so I still needed to convert. – João Pedro Jun 28 '22 at 06:21

2 Answers2

1

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 + ";")
João Pedro
  • 794
  • 2
  • 12
  • 28
1

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'}
pzutils
  • 490
  • 5
  • 10