2

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
5
  • you need to use javascript to convert a string dictionary to json object, (not a js guy) Commented Jun 28, 2022 at 5:30
  • 1
    What do you mean by "cannot"? The quotes are optional in JS, so that input is perfectly valid JS. Commented Jun 28, 2022 at 5:31
  • Does this answer your question? Convert Python dictionary to JSON array Commented Jun 28, 2022 at 5: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. Commented Jun 28, 2022 at 6: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. Commented Jun 28, 2022 at 6:21

2 Answers 2

5

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'}
answered Jun 28, 2022 at 6:26
Sign up to request clarification or add additional context in comments.

2 Comments

This should be the accepted answer, it is much more efficient and easier to understand than the other answer.
The OP's answer to their own question is not as good as this one.
2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.