Pages

Saturday, June 29, 2019

Parsing JSON on Command Line or in a Shell Script

Couple of options:

1. If you do not have the flexibility of installing new utilities, or simply prefer working with existing tools, one option to consider is to make use of Python's JSON module.

One or more statements can be executed as a unit with the help of Python interpreter's -c option.

eg.,

Following example fetches Coordinated Universal Time with the help of an API published on web, and parses the returned JSON with the help of Python's JSON module to extract the current timestamp.

$ curl -s -X GET  -H "Content-Type: application/json" http://worldclockapi.com/api/json/utc/now | json_reformat
{
    "$id": "1",
    "currentDateTime": "2019-05-21T00:00Z",
    "utcOffset": "00:00:00",
    "isDayLightSavingsTime": false,
    "dayOfTheWeek": "Tuesday",
    "timeZoneName": "UTC",
    "currentFileTime": 132028704477448626,
    "ordinalDate": "2019-141",
    "serviceResponse": null
}

% UTC_DATA=$(curl -s -X GET  -H "Content-Type: application/json" http://worldclockapi.com/api/json/utc/now)
% CURTIMESTAMP=$(python -c "import sys, json; props = json.loads('$UTC_DATA'); print props['currentDateTime']")

% echo $CURTIMESTAMP
2019-05-21T00:01Z

Here's another example that extracts the value of more than one attribute in a shell.

UTC_ATTR=$(python -c "import sys, json; props = json.loads('$UTC_DATA'); print 'TIMESTAMP={0} TZ={1} DAY={2} DayLightSavings={3}' \
   .format(props['currentDateTime'], props['timeZoneName'], props['dayOfTheWeek'], props['isDayLightSavingsTime'])")

UTC_ATTR_ARR=($UTC_ATTR)

$ for ATTR in "${UTC_ATTR_ARR[@]}"
> do
>  echo $ATTR
> done
TIMESTAMP=2019-05-21T00:01Z
TZ=UTC
DAY=Tuesday
DayLightSavings=False
To be continued ..

No comments:

Post a Comment