如何用Python删除JSON键值对?移除指定节点的Id键值对
Clean Up JSON: Remove
Id Key from Specific Nodes Alright, let's walk through how to clean up your given JSON by removing any Id key-value pairs from the Meat object, each element in the Fruit array, and the Vegetables object (only if the Id exists in those spots).
Original JSON
{ "Food" : { "Abc" : "xyz", "Meat" : { "kind" : "Turkey", "Size" : {}, "Id" : "9747" }, "Fruit" : [ { "Name" : "Orange", "Code" : "Fr", "NewCode" : "Fu1" }, { "Name" : "Apple", "Code" : "App", "Id" : "23" }, { "Name" : "Grape", "Code" : "Grp" } ], "Vegetables" : {} } }
Step-by-Step Solution (Using JavaScript)
Here's a straightforward way to handle this with JavaScript—you can adapt the core logic to other languages like Python if needed:
// Parse the JSON string into a JavaScript object const foodData = JSON.parse(`{ "Food" : { "Abc" : "xyz", "Meat" : { "kind" : "Turkey", "Size" : {}, "Id" : "9747" }, "Fruit" : [ { "Name" : "Orange", "Code" : "Fr", "NewCode" : "Fu1" }, { "Name" : "Apple", "Code" : "App", "Id" : "23" }, { "Name" : "Grape", "Code" : "Grp" } ], "Vegetables" : {} } }`); // 1. Remove Id from Meat object if it exists if (foodData.Food.Meat?.Id) { delete foodData.Food.Meat.Id; } // 2. Remove Id from each element in the Fruit array foodData.Food.Fruit.forEach(fruit => { if (fruit.Id) { delete fruit.Id; } }); // 3. Remove Id from Vegetables object if it exists if (foodData.Food.Vegetables?.Id) { delete foodData.Food.Vegetables.Id; } // Convert the cleaned object back to a nicely formatted JSON string const cleanedJson = JSON.stringify(foodData, null, 2); console.log(cleanedJson);
Cleaned JSON Result
After running the above code, you'll get this cleaned-up output:
{ "Food": { "Abc": "xyz", "Meat": { "kind": "Turkey", "Size": {} }, "Fruit": [ { "Name": "Orange", "Code": "Fr", "NewCode": "Fu1" }, { "Name": "Apple", "Code": "App" }, { "Name": "Grape", "Code": "Grp" } ], "Vegetables": {} } }
Key Notes
- We use optional chaining (
?.) and existence checks before deletingIdto avoid errors if the key isn't present in a node. - The logic handles mixed cases where some nodes have
Idand others don't—only existingIdpairs get removed.
内容的提问来源于stack exchange,提问作者user3117045




