João Pedro
João Pedro

Reputation: 970

How to convert a dictionary into a javascript object

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?

Upvotes: 2

Views: 3303

Answers (2)

pzutils
pzutils

Reputation: 530

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'}

Upvotes: 5

João Pedro
João Pedro

Reputation: 970

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 + ";")

Upvotes: 2

Related Questions