Hướng dẫn python json remove element

1.I was trying to use python to delete a particular key and its value in a JSON file. Here is the JSON file structure:

Nội dung chính

  • Answer #1:
  • Answer #2:
  • How do I remove a field from a JSON file?
  • How do I remove a property from a JSON object?
  • How do you edit a JSON object in Python?
  • How do you remove a key value pair from a JSON object?

Nội dung chính

  • Answer #1:
  • Answer #2:
  • How do I remove a field from a JSON file?
  • How do I remove a property from a JSON object?
  • How do you edit a JSON object in Python?
  • How do you remove a key value pair from a JSON object?
[
  {
    "_id": {
      "$oid": "6066af7bcb0716461578fa70"
    },
    "FileName": "copy_of_ex_fts.csv",
    "BriefInfo": "",
    "Size": "13.532KB",
    "UserName": "12795757"
    "data":"123"
  }
]

I wrote some code to remove key "data" and "UserName" with their values but I only can remove the data and its value not for the "UserName". Can someone give me some suggestions for fixing this bug?

2.Here is the code for implementation. Firstly just open the JSON file and load the data. Then to check if the key "data" and "UserName" are in it or not. If yes, delete these keys and their value.

jsonFile = open('./dataNewJson.json', 'r')
    values = json.load(jsonFile)
    for element in values:
        if 'data' in element:
            del element['data']
            print("check")
        elif 'BriefInfo' in element:
            del element['BriefInfo']
        elif 'UserName' in element:
            print("SSS")
            del element['UserName']
    values = dumps(values, indent = 2)

Question :

Delete an element in a JSON object

I am trying to loop through a list of objects deleting an element from each object. Each object is a new line. I am trying to then save the new file as is without the element contained within the objects. I know this is probably a simple task but I cannot not seem to get this work. Would be grateful if somebody could offer a hand. Thanks.

{
"business_id": "fNGIbpazjTRdXgwRY_NIXA",
"full_address": "1201 Washington AvenCarnegie, PA 15106",
"hours": {
    "Monday": {
        "close": "23:00",
        "open": "11:00"
    },
    "Tuesday": {
        "close": "23:00",
        "open": "11:00"
    },
    "Friday": {
        "close": "23:00",
        "open": "11:00"
    },
    "Wednesday": {
        "close": "23:00",
        "open": "11:00"
    },
    "Thursday": {
        "close": "23:00",
        "open": "11:00"
    },
    "Saturday": {
        "close": "23:00",
        "open": "11:00"
    }
},
"open": true,
"categories": ["Bars", "American (Traditional)", "Nightlife", "Lounges", "Restaurants"],
"city": "Carnegie",
"review_count": 7,
"name": "Rocky's Lounge",
"neighborhoods": [],
"longitude": -80.0849416,
"state": "PA",
"stars": 4.0,
"latitude": 40.3964688,
"attributes": {
    "Alcohol": "full_bar",
    "Noise Level": "average",
    "Music": {
        "dj": false
    },
    "Attire": "casual",
    "Ambience": {
        "romantic": false,
        "intimate": false,
        "touristy": false,
        "hipster": false,
        "divey": false,
        "classy": false,
        "trendy": false,
        "upscale": false,
        "casual": false
    },
    "Good for Kids": true,
    "Wheelchair Accessible": true,
    "Good For Dancing": false,
    "Delivery": false,
    "Dogs Allowed": false,
    "Coat Check": false,
    "Smoking": "no",
    "Accepts Credit Cards": true,
    "Take-out": true,
    "Price Range": 1,
    "Outdoor Seating": false,
    "Takes Reservations": false,
    "Waiter Service": true,
    "Wi-Fi": "free",
    "Caters": false,
    "Good For": {
        "dessert": false,
        "latenight": false,
        "lunch": false,
        "dinner": false,
        "brunch": false,
        "breakfast": false
    },
    "Parking": {
        "garage": false,
        "street": false,
        "validated": false,
        "lot": true,
        "valet": false
    },
    "Has TV": true,
    "Good For Groups": true
},
"type": "business"

}

I need to remove the information contained within the hours element however the information is not always the same. Some contain all the days and some only contain one or two day information. The code i’ve tried to use is Pyton that I have search throughout the day to use with my problem. I am not very skilled with Python. Any help would be appreciated.

import json

with open('data.json') as data_file:
data = json.load(data_file)
for element in data: 
        del element['hours']

Sorry Just to Add the error I am getting when running the code is
TypeError: ‘unicode’ object does not support item deletion

Answer #1:

Let’s assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT
So, as you can see, I added the code to write the data back to the file.
If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn’t be able to open the file in write mode and get a new file descriptor to write into.

I hope it’s clear enough…

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

Answer #2:

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How do I remove a field from a JSON file?

To delete an element however: var json = { 'name': John Doe, 'nickname': Johnny } var key = "name"; delete json[key];

How do I remove a property from a JSON object?

JavaScript | Remove a JSON attribute..

This keyword deletes both the value of the property and the property itself..

After deletion, the property is not available for use before it is added back again..

This operator is created to be used on object properties, not on variables or functions..

How do you edit a JSON object in Python?

How to update a JSON file in Python.

a_file = open("sample_file.json", "r").

json_object = json. load(a_file).

a_file. close().

print(json_object).

json_object["d"] = 100..

a_file = open("sample_file.json", "w").

json. dump(json_object, a_file).

a_file. close().

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

To remove JSON object key and value with JavaScript, we use the delete operator.