Remove array from json python

This is the content of my json file:

{
  "tabID": [
    {
      "dat": [1, "q"],
      "opt": []
    }
  ]
}

I'm building a python app that process that json file and I need to remove "opt":[].

I've tried next code:

data['tabID'][0].remove('data') 

But it doesn't work.

Could you give me any advice? Thanks.

Olvin Roght

7,2202 gold badges15 silver badges33 bronze badges

asked Jun 1, 2020 at 21:15

Remove array from json python

2

Make it a dict and pop the key.

Fixed an error in your JSON. Working example is at https://repl.it/repls/FrighteningPungentEquipment or as actual code:

import json

the_json_string = '{"tabID":[{"dat":[1, "q"],"opt":[] }]}'

obj = json.loads(the_json_string)
obj['tabID'][0].pop('opt')

print(json.dumps(obj))

Olvin Roght

7,2202 gold badges15 silver badges33 bronze badges

answered Jun 1, 2020 at 21:21

iScriptersiScripters

4053 silver badges13 bronze badges

3

Delete a JSON object from a list in Python #

To delete a JSON object from a list:

  1. Parse the JSON object into a Python list of dictionaries.
  2. Use the enumerate() function to iterate over the iterate over the list.
  3. Check if each dictionary is the one you want to remove and use the pop() method to remove the matching dict.

Copied!

import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_list = json.load(f) # 👇️ [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}] print(my_list) for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2))

The example shows how to delete a JSON object from an array of objects in a file.

You can use the same approach to delete a JSON object from an array of objects outside of a file.

Copied!

import json my_json = '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]' my_list = json.loads(my_json) for idx, dictionary in enumerate(my_list): if dictionary['id'] == 2: my_list.pop(idx) # 👇️ [{'id': 1, 'name': 'Alice'}] print(my_list) json_again = json.dumps(my_list) print(json_again) # 👉️ '[{"id": 1, "name": "Alice"}]'

If your JSON is located in a file, use the json.load() method to parse the json.

The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.

The next step is to iterate over the list and check if a key in each dictionary has a specific value.

Copied!

import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_list = json.load(f) # 👇️ [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}] print(my_list) for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2))

Once we find the matching dictionary, we have to use the list.pop() method to remove it from the list.

The list.pop method removes the item at the given position in the list and returns it.

You can also add a break statement if you only want to remove 1 dictionary from the list.

Copied!

for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) break

This saves you some time in needless iterations if the dictionary is towards the beginning of the list.

The last step is to open a new file (new-file.json) in the example, serialize the list to json and write it to the file.

Copied!

new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2))

How do you remove an array from a JSON object in Python?

You can use del statement: del data['tabID'][0]['opt'] . For things this simple, post running code so we can just copy/paste for experimenting.

How do you remove a key value pair from a JSON object in Python?

Deleting key:value pairs using del . Deleting key:value pairs using pop() ..
key is the key to be removed..
None specifies that if the key is found, then delete it. Else, do nothing..
We can also specify a custom message in place of 'None' for cases where key is not found..

How do you remove a key value pair from a JSON object?

JsonObject::remove() removes a key-value pair from the object pointed by the JsonObject . If the JsonObject is null, this function does nothing.

How do I delete a line in JSON?

You really should load your json with json. load(), filter and then json. dump() it. ... .
The initial code which you presented would work for normal text file, just replace line. strip() with line. startswith('sometext'). ... .
I solved it with that way. Thanks for all help. ^^.