Home > Software engineering >  Remove null from a json data (python)
Remove null from a json data (python)

Time:05-14

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.

CodePudding user response:

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:

CodePudding user response:

Try this code:

Dataset2 = list()
for data in Dataset:
    if data not null:
        Dataset2.append(data)
Dataset = Dataset2
del Dataset2

CodePudding user response:

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 != "null"] for k, v in data.items()}
  • Related