Delete a key from JSON (python)

Question:

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?

Asked By: Brell

||

Answers:

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"
        }
    ]
    }
}
}
Answered By: user20843299
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.