Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nulls, instead of Nones, in JSON Data with Python

I'm working with the following data:

[{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]

When I attempt to assign this data to a variable in Python (with the aim of parsing it out), I receive the following error message:

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

From my research, it appears that the None is Python's null. What I'm wondering is, is it possible to change the null's in my data to None's using Python?

I've tried creating a string out of the data, assigning it to data, and replacing the null's that way:

data = data.replace('null','None')

but that results in a string of the data itself:

data = '[{"title": None, "metric1": 361429, "metric2": 36,},{"title": None, "metric1": 253798, "metric2": 48}]'

and I can't figure out how to turn it from a string back into JSON.

EDIT: I am copying and pasting this data into the Python interpreter from a separate source.

like image 351
Daniel Avatar asked Mar 03 '15 23:03

Daniel


People also ask

How are nulls represented in JSON?

If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.

Are nulls allowed in JSON?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

How do you handle a null response in JSON?

Using simple java rules. Check if the array is empty, if the array does not exist and you try to get it, it just returns null. Just handle it. Don't continue parsing if you know its going to fail.

How do you convert null to none in Python?

Use the json. loads() method to convert JSON NULL values to None in Python.


2 Answers

Much simpler!

Just assign None to null before assigning that list to a variable:

null = None
var = [{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]

Then you won't need to do the rather unnecessary conversion to a string (and back to a Python object with json.loads) only to replace null by None.

But that is only really necessary if you're copy-pasting that code from some source. Otherwise, the canonical answer is to use json.loads (or json.load).

like image 181
Oliver W. Avatar answered Sep 19 '22 08:09

Oliver W.


As is mentioned above, you don't need to replace "null" for "None"

Just

import json
parsed_data = json.loads(data)
like image 34
levi Avatar answered Sep 22 '22 08:09

levi