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.
Parse JSON - Convert from JSON to Python If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
A JSON object is usually intended to be used as a storage or inter-process communication format. That's why it is in Python the universal flat format accepted by write() : a string object.
dumps() json. dumps() function converts a Python object into a json string. skipkeys:If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
Python supports JSON through a built-in package called json. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.
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, ...}' info = json.loads(data_from_api) # info is now a python dictionary (or list as appropriate) representing your Json
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)
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 > }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With