67

The Train status API I use recently added two additional key value pairs (has_arrived, has_departed) in the JSON object, which caused my script to crash.

Here's the dictionary:

{
"response_code": 200,
  "train_number": "12229",
  "position": "at Source",
  "route": [
    {
      "no": 1,
      "has_arrived": false,
      "has_departed": false,
      "scharr": "Source",
      "scharr_date": "15 Nov 2015",
      "actarr_date": "15 Nov 2015",
      "station": "LKO",
      "actdep": "22:15",
      "schdep": "22:15",
      "actarr": "00:00",
      "distance": "0",
      "day": 0
    },
    {
      "actdep": "23:40",
      "scharr": "23:38",
      "schdep": "23:40",
      "actarr": "23:38",
      "no": 2,
      "has_departed": false,
      "scharr_date": "15 Nov 2015",
      "has_arrived": false,
      "station": "HRI",
      "distance": "101",
      "actarr_date": "15 Nov 2015",
      "day": 0
    }
  ]
}

Not surprisingly, I got the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined

If I am not mistaken, I think this is because the boolean value in the JSON response is false/true whereas Python recognizes False/True. Is there any way around it?

PS: I tried converting the JSON response of has_arrived to string and then converting it back to a boolean value, only to find out that I'll always get a True value if there's any character in the string. I am kinda stuck here.

6

8 Answers 8

78

Even though Python's object declaration syntax is very similar to Json syntax, they're distinct and incompatible. As well as the True/true issue, there are other problems (eg Json and Python handle dates very differently, and python allows single quotes and comments while Json does not).

Instead of trying to treat them as the same thing, the solution is to convert from one to the other as needed.

Python's native json library can be used to parse (read) the Json in a string and convert it into a python object, and you already have it installed...

# Import the library
import json
# Define a string of json data
data_from_api = '{"response_code": 200, ...}'
data = json.loads(data_from_api)
# data is now a python dictionary (or list as appropriate) representing your Json

You can convert python objects to json too...

data_as_json = json.dumps(data)

Example:

# Import the json library
import json

# Get the Json data from the question into a variable...
data_from_api = """{
"response_code": 200,
  "train_number": "12229",
  "position": "at Source",
  "route": [
    {
      "no": 1, "has_arrived": false, "has_departed": false,
      "scharr": "Source",
      "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015",
      "station": "LKO", "actdep": "22:15", "schdep": "22:15",
      "actarr": "00:00", "distance": "0", "day": 0
    },
    {
      "actdep": "23:40", "scharr": "23:38", "schdep": "23:40",
      "actarr": "23:38", "no": 2, "has_departed": false,
      "scharr_date": "15 Nov 2015", "has_arrived": false,
      "station": "HRI", "distance": "101",
      "actarr_date": "15 Nov 2015", "day": 0
    }
  ]
}"""

# Convert that data into a python object...
data = json.loads(data_from_api)
print(data)

And a second example showing how the True/true conversion happens. Note also the changes to quotation and how the comment is stripped...

info = {'foo': True,  # Some insightful comment here
        'bar': 'Some string'}

# Print a condensed representation of the object
print(json.dumps(info))

> {"bar": "Some string", "foo": true}

# Or print a formatted version which is more human readable but uses more bytes
print(json.dumps(info, indent=2))

> {
>   "bar": "Some string",
>   "foo": true
> }
6
  • I don't know if I fully comprehend what you've mentioned, but, as you've answered, when i tried to initialize the data_from_api variable, it gave the same error (name false is not defined). So I initialized the dictionary as a string ( data_from_api=' <dict> ' and then I used the loads function which worked as expected. What I wanna know is that the dictionary which I get from api is very big(I have reduced the size in the question for the sake of simplicity), is the the most efficient way to do it?
    – Jarwin
    Nov 15, 2015 at 18:32
  • The problem is you've got a string that contains Json and you're treating it like a string that contains Python. The two are not the same. data_from_api should be a string containing exactly what you posted in the question. Whether you read this from a file or from a Http request depends on the source of the data which you haven't specified in your question. The json library will convert json strings into python objects and vice-versa
    – Basic
    Nov 15, 2015 at 21:23
  • I've added an example where the data you provided is treated as a multi-line string literal. Does that make things clearer? ("""...""" is a way of defining strings that span multiple lines and containing "'s). Once you've got a variable containing the json, the conversion is simple. How you populate that variable will depend on where you're getting your data. For next time, including that information / a code snippet in the question would've been helpful.
    – Basic
    Nov 15, 2015 at 21:39
  • I would like to add one more thing that would work for people who are reading from a file. with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile: data = json.dumps(jsonfile.read()) Then follow the above answer i.e. data_json = json.loads(data) Mar 20, 2020 at 15:58
  • 1
    I love when I google this question and come to this SO page only to discover that at some point in the past, I upvoted this question and answer. I believe this is my fourth visit to this page, wish I could upvote it more.
    – ingernet
    Apr 6 at 20:03
9

You can also do a cast to boolean with the value. For example, assuming that your data is called "json_data":

value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value

boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value

It's kind of hackey, but it works.

5

Instead of doing eval on the answer, use the json module.

5

It is possible to utilize Python's boolean value for int, str, list etc.

For example:

bool(1)     # True
bool(0)     # False

bool("a")   # True
bool("")    # False

bool([1])   # True
bool([])    # False

In Json file, you can set

"has_arrived": 0,

Then in your Python code

if data["has_arrived"]:
    arrived()
else:
    not_arrived()

The issue here is not to confuse 0 indicated for False and 0 for its value.

0
3
"""
String to Dict (Json): json.loads(jstr)
Note: in String , shown true, in Dict shown True
Dict(Json) to String: json.dumps(jobj) 
"""    
>>> jobj = {'test': True}
>>> jstr = json.dumps(jobj)
>>> jobj
{'test': True}
>>> jstr
'{"test": true}'
>>> json.loads(jstr)
{'test': True}
-1

I would like to add one more thing that would work for people who are reading from a file.

with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile:
            data = json.dumps(jsonfile.read())

Then follow the above accepted answer i.e.

data_json = json.loads(data)
-3

{ "value": False } or { "key": false } is not a valid json https://jsonlint.com/

5
  • 3
    how { "key": false } is not a valid json? Apr 15, 2020 at 7:37
  • because it can be read from a file. in which case, both should be treated as strings Apr 23, 2020 at 13:17
  • 1
    You say { "key": false } is not valid json and give link to validator that says it is valid. Can you elaborate?
    – Mulperi
    Aug 19, 2021 at 5:20
  • That is incorrect, w3schools.com/js/js_json_datatypes.asp and json.org/json-en.html both state that boolean values are allowed.
    – Luk164
    Sep 9, 2021 at 6:47
  • simply, a wrong answer. Dec 24, 2021 at 11:10
-3

json.loads cant parse the pythons boolean type (False, True). Json wants to have small letters false, true

my solution:

python_json_string.replace(": True,", ": true,").replace(": False,", ": false,")

1
  • 1
    it does not work as it replaces the keys with indexes [0], [1] etc Jul 18, 2020 at 1:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.