удаление json in python

To delete a JSON object in Python, you need to parse the JSON string into a Python object, remove the desired element, and then stringify the modified object back into a JSON string. Here's an example:

main.py
import json

# Sample JSON string
json_string = '''
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
'''

# Parse the JSON string into a Python object
data = json.loads(json_string)

# Remove an element from the object
del data['age']

# Convert the modified object back to a JSON string
new_json_string = json.dumps(data)

# Print the updated JSON string
print(new_json_string)
386 chars
23 lines

This will output the following JSON string:

main.py
{"name": "John", "city": "New York"}
37 chars
2 lines

In this example, we parse the given json_string using json.loads() to create a Python dictionary called data. We then use the del keyword to remove the "age" element from the dictionary. Finally, we use json.dumps() to convert the modified dictionary back to a JSON string, which is stored in new_json_string and printed to the console.

Make sure to replace json_string with your actual JSON string and provide the correct key of the element you want to remove inside the del statement.

related categories

gistlibby LogSnag