Jack Hanna
Jack Hanna

Reputation: 167

Why can't I use true/false/null in a Python object fed to json.dumps()?

...

import json

raw_json = {
'a':'aa',
'b':'bb',
'c':'cc',
'd':true,
'e':false,
'f':null
}

json_dump = json.dumps(raw_json)
json_load = json.loads(json_dump)

What am I doing wrong/need to do?

Also, I'm coming from a javascript background so it has been a pain trying to learn the conventions and terms. What are the 'u's prepending each json key in the other thread's link following 'd2'?

Upvotes: 2

Views: 12005

Answers (4)

TCamara
TCamara

Reputation: 179

Coming in late for an answer, but here is my take: you could just write raw_json as:

raw_json = {
    'a':'aa',
    'b':'bb',
    'c':'cc',
    'd':bool(1),
    'e':bool(0),
    'f':None
           }

"None" is the equivalent of null. And the boolean function helps create the your "true" and "false" for you.

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295472

You can embed your raw JSON in code if you do so in a string (which, if you're using good practices to read data from disk or network, is what you'll have anyhow):

# similar to what you'd get from raw_json=open('in.json', 'r').read()
raw_json = '''{
'a':'aa',
'b':'bb',
'c':'cc',
'd':true,
'e':false,
'f':null
}'''

python_struct = json.loads(raw_json)
json_again = json.dumps(raw_json)

Because true, false and null are all inside of the string, the parser doesn't try to read them as valid Python, so json.loads() is able to see them as they were originally written.

Upvotes: 4

John Starich
John Starich

Reputation: 619

In your JSON variable raw_json, you need to capitalize True and False. In Python, Boolean values are capitalized for true and false. When you serialize it into JSON, they will be lower cased. Also, None is the Python equivalent of null.

When you perform a JSON dump, you are taking in a Python dictionary (which must be valid Python) and outputting a string which follows the JSON standard. The conversion visually changes the upper cased True, False, and None into their JSON equivalents true, false, and null.

To answer why there are us on the strings, that is referring to the strings being Unicode strings.

Upvotes: 5

Wondercricket
Wondercricket

Reputation: 7872

In Python, you need True, False, and None.

raw_json = {
    'a':'aa',
    'b':'bb',
    'c':'cc',
    'd': True,
    'e': False,
    'f': None
}

Upvotes: 1

Related Questions