Python json none to null

Python json none to null

Last updated: Feb 18, 2023
Reading time · 2 min

banner

# Convert JSON NULL values to None using Python

Use the json.loads() method to convert JSON NULL values to None in Python. The json.loads method parses a JSON string into a native Python object.

Conversely, the json.dumps method converts a Python object to a JSON formatted string.

Copied!
import json my_json = r'' my_dict = json.loads(my_json) print(type(my_dict)) # 👉️ print(my_dict) # 👉️

convert json null values to none

The example shows how to convert null values to None using the json.loads() method.

# Convert JSON NULL values to Python None values

The json.loads method parses a JSON string into a native Python object.

Copied!
import json json_str = r'' my_dict = json.loads(json_str) print(type(my_dict)) # 👉️

convert json null values to python none values

The process of converting a JSON string to a native Python object is called deserialization.

# Convert Python None values to JSON NULL values

You can use the json.dumps method to convert a Python object to a JSON formatted string.

Copied!
import json my_json = r'' # ✅ convert NULL values to None (JSON string to Python object) my_dict = json.loads(my_json) print(type(my_dict)) # 👉️ print(my_dict) # 👉️ # ✅ convert None to null (Python object to JSON string) my_json_again = json.dumps(my_dict) print(my_json_again) # 👉️ ''

convert python none values to json null

The process of converting a native Python object to a JSON string is called serialization.

You can also have None keys in Python objects, but it should generally be avoided.

Copied!
import json my_dict = 'name': 'Bobby', None: None> print(my_dict) # 👉️ my_json = json.dumps(my_dict) print(my_json) # 👉️ '' my_dict_again = json.loads(my_json) print(my_dict_again) # 👉️

We started with a Python object that has a None key and a None value.

When we converted the object to JSON, both the key and the value got converted to null .

When we parsed the JSON string into a Python object, the value got converted to None , but the key is still the string null .

This is because JSON keys must be of type string . If we pass a key of any other type to the json.dumps() method, the key automatically gets converted to a string.

Once the key is converted to a string, parsing the JSON string will return a string key in the Python object.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How json dumps None to empty string

I want Python’s None to be encoded in json as empty string how? Below is the default behavior of json.dumps .

>>> import json >>> json.dumps(['foo', ]) '["foo", ]' 

Should I overwrite the json encoder method or is there any other way? Input data is not that simple as in above example, on every request it could be changed to different data structure. Its difficult to write a function for changing data structure.

My input data is not that simple as in above example, so I am looking to change the None to empty string through json.dumps .

It should be noted that None is not the same thing as an empty string; so keep that in mind when converting. The correct equivalent of None is null

@BurhanKhalid Yes you are right but I have to send this json data to mobile side and there Iphone and Android guys having problem with null , therefore I am converting this to empty strings.

The thing to be careful of is if in your code the difference between None and » is significant, and you’re expecting data back; you have some potential ambiguity between whether a returned » is indeed a » or is meant to be converted back to None again.

4 Answers 4

In the object you’re encoding, use an empty string instead of a None .

Here’s an untested function that walks through a series of nested dictionaries to change all None values to » . Adding support for lists and tuples is left as an exercise to the reader. 🙂

import copy def scrub(x): ret = copy.deepcopy(x) # Handle dictionaries. Scrub all values if isinstance(x, dict): for k,v in ret.items(): ret[k] = scrub(v) # Handle None if x == None: ret = '' # Finished scrubbing return ret 

It would be better to process the data you want to encode and replace None s with empty strings. After all, that is what you want.

Here is a slightly improved version that handles lists and tuples as well:

def scrub(x): # Converts None to empty string ret = copy.deepcopy(x) # Handle dictionaries, lits & tuples. Scrub all values if isinstance(x, dict): for k, v in ret.items(): ret[k] = scrub(v) if isinstance(x, (list, tuple)): for k, v in enumerate(ret): ret[k] = scrub(v) # Handle None if x is None: ret = '' # Finished scrubbing return ret 

I used it when using jsonschmea module. It seems that it cannot handle None type, and throws: jsonschema.exceptions.ValidationError: None is not of type u’string’ . So this takes care of the problem.

You can actually use the json.JSONEncoder, if you have an object with lists, tuples, dicts, strings and None, you can use the class shown afterwards to replace None to empty string.

default is the method originally used to convert non json types to python, this time we use it to convert the None to empty string.

encode is used to encode the json, that’s why we use it with the new default to use the new method

class NoneToEmptyJSON(json.JSONEncoder): def default(self, o): if o == None: o = '' elif type(o) == dict: return elif type(o) == list or type(o) == tuple: return [self.default(item) for item in o] return o def encode(self, o): return super().encode(self.default(o)) 

Then instead of dump, you use encode with the class

You can also use params if you want indent or other things this way:

NoneToEmptyJSON(ensure_ascii=False, indent=2).encode(['foo', ]) 

Источник

Convert Python None to JavaScript null

For use in a High Charts script. Unfortunately JavaScript is stumbling when it encounters the None value because actually what I need is null . How can I best replace None with null , and where should I handle this — in the Django View or in the JavaScript?

What version are you using of simplejson? According to the documentation, None should be converted to null automatically (see simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/…)

2 Answers 2

If you’re using Python 2.6 or later, you can use the built-in json module:

>>> import json >>> json.dumps([1, 2, 3, None, 4]) '[1, 2, 3, null, 4]' 

That worked. Not sure why simplejson didn’t do it. Any disadvantage in using json as opposed to simplejson in Django?

Ok — now simplejson seems to work to. Not sure whant was happeing but I was definitely getting None in my json dump yesterday

I’ve never run any benchmarks comparing them myself but at stackoverflow.com/questions/712791/… people are saying simplejson is faster. (And of course, if you need compatibility with Python 2.5 the built-in json module is out.)

When I tried the accepted solution json.dumps() returned NaN values rather than the null JavaScript is looking for. Therefore I found another solution that does not use json or simplejson packages. The following solution uses type checking of None in Django. The solution that inspired me can be found here.

I used it in my code as follows to populate a Javascript array correctly:

The none object in Django will check the None value offered by python. It doesn’t seem to correctly handle np.NaN objects though.

Источник

Читайте также:  Варианты использования try java
Оцените статью