0

For example if you have the following JSON object(remove the semicolon for python):

values = {
    a: 1,
    b: {
        c: 2,
        d: { e: 3 }
    },
    f: 4,
    g: 5   
};

If you try to print values in JS, it will work fine. But in Python it will return an error NameError: name 'a' is not defined which means these variables aren't defined and needs to be set as strings.

Lets say I need to load it into python without manually converting these undefined variables to string. I tried json.loads but it didn't work. Any other built-in functions to do this work? It seems in JS it automatically treats them as strings if they are not defined or just ignores the fact that they are defined or not?

Any explanation?

2
  • 3
    That's not JSON, that's a JS object. Commented Sep 18, 2013 at 10:16
  • Use JSON.stringify(values) Commented Sep 18, 2013 at 10:18

1 Answer 1

2

I tried json.loads but it didn't work.

That's because what you've quoted isn't JSON, it's a JavaScript object initializer being assigned to something (probably a variable).

Here's the equivalent JSON:

{
    "a": 1,
    "b": {
        "c": 2,
        "d": { "e": 3 }
    },
    "f": 4,
    "g": 5   
}

Items of note:

  • No variable, no =
  • The top level must be an object (e.g., {...}) or an array (e.g., [...]).
  • Property names (keys) must be in double quotes
  • Strings must be in double quotes (you don't have any strings in your example, but if you did, single quotes — for instance — wouldn't be valid)
  • No ; at the end
Sign up to request clarification or add additional context in comments.

1 Comment

ah ok! I thought you can set it equal to a variable.

Your Answer

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