1

Can someone suggest a way to serialise a Python dictionary to JavaScript source code describing an equivalent object?

Note that this is different from JSON serialisation. In particular, the following example is important to me:

x = { True: 1, False: 0 }

Serialising this with json.dumps(x) results in:

{ "true": 1, "false": 0 }

What I want is:

{ true: 1, false: 0 }

This is a valid object declaration in JavaScript but is not valid JSON. Similar problems occur when using any non-string type as a dictionary key.

2
  • But what is the difference knowing that in JS keys are string type anyways? Commented Jan 24, 2020 at 13:52
  • @Andrey - that's not true. It's perfectly valid to declare a JS object with boolean keys. x = { true: 1, false: 2 }; console.log(x[true]); runs just fine. Commented Jan 24, 2020 at 13:56

1 Answer 1

1

In javascript object keys can only be strings or Symbols

You can access the object properties with true/false because javascript convert them to strings, you can see that they are actually string with:

var x = { true: 1, false: 0 }
console.log(Object.keys(x)) // ["true", "false"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.