You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用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 deleting Id to avoid errors if the key isn't present in a node.
  • The logic handles mixed cases where some nodes have Id and others don't—only existing Id pairs get removed.

内容的提问来源于stack exchange,提问作者user3117045

火山引擎 最新活动