Jarwin Jarwin - 4 months ago 32
JSON Question

Converting "true" (JSON) to Python equivalent "True"

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.

Answer

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 comment syntax).

The solution is to convert from one to the other.

Use the json library to parse the data...

data_from_api = ...
info = json.loads(data_from_api)

You can convert python objects to json too...

info_as_json = json.dumps(info)

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...
info = json.loads(data_from_api)
print(info)