Python json удалить элемент

Как удалить элемент из .json файла?

Подскажите, пожалуйста, каким образом можно удалить элемент из этого файла по ключу в Python? Спасибо!

3 ответа 3

Из вопроса не очень понятно, что вы пытаетесь удалить. Вот пример как удалить из первого элемента salary

import json a = '''< "personal": [ < "name": "Вася", "salary": 5000 >, < "name": "Саша", "salary": 6000 >]>''' dict_ = json.loads(a) dict_["personal"][0].pop("salary") print(dict_) 
import json with open("test.json", encoding="utf8") as file: dict_ = json.load(file) dict_["personal"][0].pop("salary") with open("test.json", "w", encoding="utf8") as file: json.dump(dict_, file, ensure_ascii=False) 

Спасибо всем за комментарии. Нашел следующий вариант (так как непонятно было, нужно ли удалять первый или какой-то неопределенный элемент .json — файла):

user_for_del = str(input('Введите имя удаляемого сотрудника\n')) print(user_for_del) with open('personal.json', 'r', encoding='utf-8') as f: # открыли файл data = json.load(f) # загнали все из файла в переменную minimal = 0 for txt in data['personal']: print('Запись №:', minimal) print(txt['name'], ':', txt['salary']) if txt['name'] == user_for_del: print('Запись будет удалена') data['personal'].pop(minimal) else: None minimal = minimal + 1 print('Итоговый результат: ') print(data) print('А теперь записываем итоговый файл') with open('personal.json', 'w', encoding='utf8') as outfile: json.dump(data, outfile, ensure_ascii=False, indent=2) 

Благодаря этой конструкции можно шерстить .json — файл, находить нужные записи и удалять . не думаю, что изобрел велосипед, но все же 🙂

Читайте также:  Popitem python 3 это

Источник

Python json удалить элемент

Last updated: Feb 19, 2023
Reading time · 4 min

banner

# Table of Contents

# 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 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) # [, # , # ] 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))

delete json object from list

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

The code assumes that you have an example.json file with the following contents.

Copied!
[ "id": 1, "name": "Alice", "age": 30>, "id": 2, "name": "Bob", "age": 35>, "id": 3, "name": "Carl", "age": 40> ]

We used an if statement to check if each object has an id property with a value of 2 .

If the condition is met, we remove the object from the list and write the result to another file.

The file with the name new-file.json has the following contents after the operation.

Copied!
[ "id": 1, "name": "Alice", "age": 30 >, "id": 3, "name": "Carl", "age": 40 > ]

Notice that the JSON object with an id of 2 got removed.

# Deleting a JSON object from an array outside 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 = '[, ]' my_list = json.loads(my_json) for idx, dictionary in enumerate(my_list): if dictionary['id'] == 2: my_list.pop(idx) # 👇️ [] print(my_list) json_again = json.dumps(my_list) print(json_again) # 👉️ '[]'

delete json object from array outside file

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

# JSON.load() vs JSON.loads()

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) # 👇️ [, , ] 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))

json load vs json loads

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.

# Use the break statement if you only want to remove 1 dictionary

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.

# Writing the result to a new file

The last step is to open a new file, 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))

The file called new-file.json reflects the changes and the original file remains unchanged.

Copied!
[ "id": 1, "name": "Alice", "age": 30 >, "id": 3, "name": "Carl", "age": 40 > ]

# Delete a JSON object from a list using a list comprehension

You can also use a list comprehension to delete a JSON object from a list.

Copied!
import json my_json = '[, ]' my_list = json.loads(my_json) # [, ] print(my_list) new_list = [dictionary for dictionary in my_list if dictionary['name'] != 'Bob'] # [] print(new_list)

We used the JSON.loads() method to convert the JSON array to a Python list of dictionaries and use a list comprehension to iterate over the list.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current dictionary doesn’t have a name key with a specific value and return the result.

The new list only contains the dictionaries that meet the condition.

# Delete a JSON object from a list using filter()

You can also use the filter() function to delete a JSON object from a list.

Copied!
import json my_json = '[, ]' my_list = json.loads(my_json) # [, ] print(my_list) new_list = list( filter(lambda x: x['name'] != 'Bob', my_list) ) # [] print(new_list)

delete json object from list using filter

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function we passed to filter() gets called with each dictionary of the list.

The lambda checks if the name key in each dictionary doesn’t have a specific value.

The filter object only contains the dictionaries for which the condition is met.

The last step is to use the list() class to convert the filter object to a list.

# 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 to delete json object using python?

I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the JSON file. My JSON file is:

I want to delete the JSON object with ename mark . As I am new to python I tried to delete it by converting objects into dict but it is not working. Is there any other way to do it? i tried this one:

5 Answers 5

Here’s a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.

#!/usr/bin/python # Load the JSON module and use it to load your JSON file. # I'm assuming that the JSON file contains a list of objects. import json obj = json.load(open("file.json")) # Iterate through the objects in the JSON and pop (remove) # the obj once we find it. for i in xrange(len(obj)): if obj[i]["ename"] == "mark": obj.pop(i) break # Output the updated file with pretty JSON open("updated-file.json", "w").write( json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) ) 

The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you’ve reached the end of the for loop (you don’t want to modify the list while you iterate through it).

Источник

Как удалить запись из json-файла в Python?

Как удалить запись из json-файла в Python

Как удалить запись из json-файла в Python

Привет всем! Давно (очень давно) я написал вот этот пост, посвященный добавлению данных в json-файл. Потом сделал видео по этому поводу, и вот вчера к видео был добавлен комментарий-просьба — сделать видео, посвященное вопросу: как удалить запись из json-файла в Python? Видео — добавлю совсем скоро, а вот текст и код — ниже. Поехали!

Итак, как добавлять записи в json-файл мы знаем. А вот как удалить ту или иную запись по ключу (мы же помним, что в целом json — это тот же словарь, а значит имеет связку «Ключ-значение»)? На самом деле — все просто. Итак, у нас имеется json-файл с данными о зарплате пользователей. Выглядит этот файл следующим образом:

Теперь напишем код, который будет в качестве входного параметра получать имя пользователя, данные о котором нам нужно удалить (фактически — это ключ), а после — если искомый ключ (имя пользователя) — будут найдены — удалять эти записи. Выглядит код следующим образом:

import json user_for_del = str(input('Введите имя сотрудника, данные о котором нужно удалить? \n')) with open('personal.json', 'r', encoding='utf-8') as f: data = json.load(f) minimal = 0 for txt in data['personal']: if txt['name'] == user_for_del: data['personal'].pop(minimal) else: None minimal = minimal + 1 with open('personal.json', 'w', encoding='utf-8') as outfile: json.dump(data, outfile, ensure_ascii=False, indent=2)

В самом начале — подключаем библиотеку json, которая упрощает работу с json 🙂
После этого — получаем переменную, которая состоит из имени пользователя, которого мы будем удалять из нашего файла (фактически — это ключ в нашем словаре).
А теперь — открываем json-файл, и делаем из него словарь (в том, что это словарь — вы можете убедиться, если выведите тип переменной data). А теперь уже — совсем просто все — обрабатываем в цикле каждый элемент словаря, и сравниваем его с нашей переменной user_for_del (имя пользователя, которого мы будему удалять из json-файла): если значение совпадает — удаляем эту запись (именно для этого нам и нужна переменная minimal, которая, фактически, служит для создания номера записи). Удалили запись? Великолепно! А теперь конвертируем наш обработанный словарь в json-файл и сохраняем изменения 🙂

UPD: вот и видео подоспело… 🙂

Надеюсь, смог вам помочь. Как всегда — в случае возникновения вопросов пишите на почту, или в Telegram.

Источник

Оцените статью