Home > other >  Delete a key from JSON (python)
Delete a key from JSON (python)

Time:01-03

I tried to delete the key ts in every machine but always I have the same error keyerror 0.

My JSON:

{
  "timestamp": "2023-01-03 10:30:39",
  "Essais": {
    "machine": {
      "temperature": [{ "ts": 1671781231183, "value": "100" }],
      "humidity": [{ "ts": 1671781231183, "value": "40" }]
    },
    "machine2": {
      "temperature": [{ "ts": 1671781231183, "value": "100" }],
      "humidity": [{ "ts": 1671781231183, "value": "40" }]
    }
  }
}

How can I delete the key ts and its value in all the JSON file?

CodePudding user response:

Here is one way you can delete the ts keys and their values from the JSON object:

import json

json_data = {"timestamp": "2023-01-03 10:30:39",
  "Essais": {
   "machine": {
    "temperature": [
     {
      "ts": 1671781231183,
      "value": "100"
     }],
     "humidity": [
     {
      "ts": 1671781231183,
      "value": "40"
     }]},
    "machine2":{
    "temperature": [
     {
      "ts": 1671781231183,
      "value": "100"
     }],
     "humidity": [
     {
      "ts": 1671781231183,
      "value": "40"
     }]}}}

def delete_ts(obj):
    if isinstance(obj, list):
        for i in obj:
            delete_ts(i)
    elif isinstance(obj, dict):
        if 'ts' in obj:
            del obj['ts']
        for key in obj:
            delete_ts(obj[key])

delete_ts(json_data)

print(json.dumps(json_data))

This will output the following JSON object:

{
"timestamp": "2023-01-03 10:30:39",
"Essais": {
    "machine": {
    "temperature": [
        {
        "value": "100"
        }
    ],
    "humidity": [
        {
        "value": "40"
        }
    ]
    },
    "machine2": {
    "temperature": [
        {
        "value": "100"
        }
    ],
    "humidity": [
        {
        "value": "40"
        }
    ]
    }
}
}
  • Related