A
A
aivspb2020-07-24 14:33:26
Python
aivspb, 2020-07-24 14:33:26

How to use python to extract data from json advice from ZONT API service?

Good day !
Can you please tell me how to extract data from json file?
I have a test.json file, with an example content:

{
  "ok": true,
  "events": [
    [
      "GuardOn-1486253766",  // id
      1486253766,            // время
      "GuardOn",             // тип
      43.871066,             // долгота
      56.166916,             // широта
      null,                  // продолжительность
      {                      // данные
          "reason": "fob",   //   причина постановки на охрану
          "fob_number": 1    //   номер брелока
      },
      false                  // тревожное?
    ],

    ...
  ]
}


How can I print only the time and type to the console?
1486253766
"GuardOn"


Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Shatalov, 2020-07-24
@aivspb

import json
from collections import namedtuple 

input_json = '''
{
    "ok": true,
    "events": [
  [
      "GuardOn-1486253766",
            1486253766,
            "GuardOn",
            43.871066,
            56.166916,
            null,
            {
                "reason": "fob",
    "fob_number": 1
            },
            false
  ]
    ]
}
'''

input_data = json.loads(input_json)

Event = namedtuple(
    "Event", 
    ("id", "time", "event_type", "longitude", 
     "latitude", "duration", "data", "is_alarm")
)

events = input_data.get("events")
for event in events:
    event_data = Event(*event)
    print(event_data.time)
    print(event_data.event_type)

S
soremix, 2020-07-24
@SoreMix

With the help of the library, surprisingly, json

import json
with open('file.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
print(data['events'][1], data['events'][2])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question