You can use a dictionary comprehension:
data = json.loads('{"foo":"5", "bar":""}')
res = {k: v if v != '' else None for k, v in data.items()}
{'foo': '5', 'bar': None}
This will only deal with the first level of a nested dictionary. You can use a recursive function to deal with the more generalised nested dictionary case:
def updater(d, inval, outval):
for k, v in d.items():
if isinstance(v, dict):
updater(d[k], inval, outval)
else:
if v == '':
d[k] = None
return d
data = json.loads('{"foo":"5", "bar":"", "nested": {"test": "", "test2": "5"}}')
res = updater(data, '', None)
{'foo': '5', 'bar': None,
'nested': {'test': None, 'test2': '5'}}
Answer from jpp on Stack Overflowpython - parse empty string using json - Stack Overflow
python 3.x - Load an empty string as a JSON in Python3 - Stack Overflow
python - How can I create the empty json object? - Stack Overflow
How to parse completely empty JSON key/values?
You can use a dictionary comprehension:
data = json.loads('{"foo":"5", "bar":""}')
res = {k: v if v != '' else None for k, v in data.items()}
{'foo': '5', 'bar': None}
This will only deal with the first level of a nested dictionary. You can use a recursive function to deal with the more generalised nested dictionary case:
def updater(d, inval, outval):
for k, v in d.items():
if isinstance(v, dict):
updater(d[k], inval, outval)
else:
if v == '':
d[k] = None
return d
data = json.loads('{"foo":"5", "bar":"", "nested": {"test": "", "test2": "5"}}')
res = updater(data, '', None)
{'foo': '5', 'bar': None,
'nested': {'test': None, 'test2': '5'}}
You can also accomplish this with the json.loads object_hook parameter. For example:
import json
import six
def empty_string2none(obj):
for k, v in six.iteritems(obj):
if v == '':
obj[k] = None
return obj
print(json.loads('{"foo":"5", "bar":"", "hello": {"world": ""}}',
object_hook=empty_string2none))
This will print
{'foo': '5', 'bar': None, 'hello': {'world': None}}
This way, you don't need additional recursion.
Use coalescing to pass it something valid.
json.loads('' or 'null')
To give another way that worked for me, I used the inline if which returns an empty string if there is no data to load: As seen below I wanted to load the request form data which is the session id
session_id = json.loads(request.form['session_id']) if request.form['session_id'] else ''
Simply:
json.loads(request.POST.get('mydata', '{}'))
Or:
data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {}
Or:
if 'mydata' in request.POST:
data = json.loads(request.POST['mydata'])
else:
data = {} # or data = None
loads() takes a json formatted string and turns it into a Python object like dict or list. In your code, you're passing dict() as default value if mydata doesn't exist in request.POST, while it should be a string, like "{}". So you can write -
json_data = json.loads(request.POST.get('mydata', "{}"))
Also remember, the value of request.POST['mydata'] must be JSON formatted, or else you'll get the same error.
Let's say I have a JSON object like this:
{"Data":[{"key1":"value1"},{"key2":"value2"},
{}]
}
If I wanted a list to look as follows: ['value1', 'value2', '']. How would I go about pulling in that null JSON key/value? Is that possible?
Thank you!
Simply use dict.get(), i.e.:
return jStr.get(to_extract, '')
See https://docs.python.org/3/library/stdtypes.html#dict.get for more details.
UPD:
Thanks to @jez for pointing out, that jStr is not guaranteed to be a dictionary. However, the result for JSON parsing is known: if it's not a dictionary, then it's a list, number or a string. In this case, wrap it into a type checking routine, e.g.:
try:
return jStr[to_extract]
except (KeyError, AttributeError):
return ''
Like Zaur, I would also have suggested jStr.get(to_extract, '') but I presume the OP's objection to this is that jStr might or might not be a dict (if it is a dict, then .get() will work in Python 2 or 3). If that's the problem, then the following might cover a broader range of cases:
try: return jStr[to_extract]
except: return ''