'Remove null from a json data (python)
When I use the Rest API to download data from Firebase, it looks like this.
{
"Dataset1": [
null,
{
"Key1": 1,
"Key2": 2
},
{
"Key1": 3,
"Key2": 4
}
],
"Dataset2": [
null,
{
"Key1": 1,
"Key2": 2
},
{
"Key1": 3,
"Key2": 4
}
]
}
Is it possible to remove the null
value before saving the data to a file? I know the null
exists because of how I designed my database, but it is too late for me to redesign the data now. I tried is_not
but no luck yet.
Solution 1:[1]
It seems it's just the first element in each list. You could just use a simple dict comprehension for this if so:
{k: v[1:] for k, v in data.items()}
If not you could use this comprehension:
{k: [e for e in v if e != None] for k, v in data.items()}
Solution 2:[2]
It looks like you've stored nodes with sequentially incrementing keys in your database (i.e. "1", "2", "3"). When you do this, Firebase interprets it as an array structure, and coerces it to a (zero-based) array when you retrieve it. And since you have no node for index 0, it adds a null
there.
To prevent this array coercion, store nodes with non-numeric keys, for example by prefixing each number with a short non-numeric value. Like "key1", "key2", "key3".
Also see:
Solution 3:[3]
Try this code:
Dataset2 = list()
for data in Dataset:
if data not null:
Dataset2.append(data)
Dataset = Dataset2
del Dataset2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Frank van Puffelen |
Solution 3 | Lucas |