19

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.

4
  • 4
    The correct way to convert a JSON string into a python object is json.loads -- no string munging necessary. Commented Mar 3, 2015 at 23:19
  • That's not a json string. The comma at the end of "metric2": 36, shouldn't be there. Commented Mar 3, 2015 at 23:59
  • 3
    It seems like you are pasting this into the python interpreter (which means its python syntax, not JSON). Is that the case, and if so, why not mention it? Commented Mar 4, 2015 at 0:02
  • @tdelaney you are correct! I am copying and pasting into the interpreter. Apologies for not mentioning; it wasn't on purpose, just a detail that slipped my mind. Good call. Commented Mar 9, 2015 at 21:37

2 Answers 2

51

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot @Oliver W.! Very clever. This is exactly what I needed. Very good insight with the copy/paste even though I forgot to mention it.
I thought it's so tricky. How about another way to convert it to None?
How simple. I would never name a name as null and could't think of that solution!
15

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

Just

import json parsed_data = json.loads(data) 

1 Comment

Thanks @levi! This makes perfect sense. Will do for future json and python endeavors. +1 for your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.