Updating a value in a multiple object JSON file

Question:

JSON file:

{
    "data": [
        {
            "id": "ec35139e-60b9-458e-95c6-0aa1db7d30d4",
            "name": "Jeffrey",
            "last_ping": "2022-11-02 17:42:00.765568",
            "last_ping_timestamp": 1667407320,
            "status": "ok",
            "secret_key": "BigBook32"
        },
        {
            "id": "4b9b05df-c9d7-4ed6-bde7-d4663414996b",
            "name": "John",
            "last_ping": "2022-11-02 17:42:00.772017",
            "last_ping_timestamp": 1667407320,
            "status": "ok",
            "secret_key": "FastSnake40"
        },
        {
            "id": "9ed15fce-2069-470a-8515-6723b28f257d",
            "name": "Jack",
            "last_ping": "2022-11-02 17:42:00.788384",
            "last_ping_timestamp": 1667407320,
            "status": "ok",
            "secret_key": "GreenComputer33"
        }
    ]
}

I have a JSON file with hundreds of objects, how can I update the "last_ping" value for one of them in python?

Asked By: EZDJSkdjs

||

Answers:

One way is to use jq and edit the json directly

Another is to convert into object/array in python, modify it programmatically, then convert it back to JSON. There are plenty of examples online. Have you tried any? Any specific errors you encounter?

Answered By: Ron

we take data then we edit the last_ping to the current time.

import json,datetime

data = {
    "data": [
        {
            "id": "ec35139e-60b9-458e-95c6-0aa1db7d30d4",
            "name": "Jeffrey",
            "last_ping": "2022-11-02 17:42:00.765568",
            "last_ping_timestamp": 1667407320,
            "status": "ok",
            "secret_key": "BigBook32"
        },
        {
            "id": "4b9b05df-c9d7-4ed6-bde7-d4663414996b",
            "name": "John",
            "last_ping": "2022-11-02 17:42:00.772017",
            "last_ping_timestamp": 1667407320,
            "status": "ok",
            "secret_key": "FastSnake40"
        },
        {
            "id": "9ed15fce-2069-470a-8515-6723b28f257d",
            "name": "Jack",
            "last_ping": "2022-11-02 17:42:00.788384",
            "last_ping_timestamp": 1667407320,
            "status": "ok",
            "secret_key": "GreenComputer33"
        }
    ]
}
data = json.dumps(data)
data = json.loads(data)

name = input("Enter name: ")
for i in data["data"]:
    if i["name"] == name:
        i["last_ping_timestamp"] = int(datetime.datetime.now().timestamp())
        i["last_ping"] = str(datetime.datetime.now())

print(data)
Answered By: Flow
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.