1

I appear to be struggling with cutting the JSON responses from CloudFlare's API.

when I CURL the https://api.cloudflare.com/client/v4/zones/xxxx/settings URL it returns all settings for the zone of my domain in a JSON response such as:

        "editable": true,
        "id": "server_side_exclude",
        "modified_on": null,
        "value": "on"
    },
    {
        "editable": false,
        "id": "sha1_support",
        "modified_on": null,
        "value": "off"
    },
    {
        "editable": false,
        "id": "sort_query_string_for_cache",
        "modified_on": null,
        "value": "off"
    },
    {
        "certificate_status": "active",
        "editable": true,
        "id": "ssl",
        "modified_on": "2016-05-18T14:38:45.665403Z",
        "value": "flexible"

This is because I am of course cutting it by piping the curl to python -m json.tool. What I am trying to achieve is basically print everything as for example:

server_side_exclude = on
sha1_support = off
sort_query_string_for_cache = off

( the ID = the value ). I have attempted to store the IDs and values in separate variables as for example:

IDs=$(curl https://api.cloudflare.com/client/v4/zones/xxxx/settings | python -m json.tool | grep id)
Values=$(curl https://api.cloudflare.com/client/v4/zones/xxxx/settings | python -m json.tool | grep value)

and then printing them next to each other for example with:

echo "$IDs = $Values"

but the empty spaces appear to cause difficulties. I have also tried to cut the reply by using awk and sed but am not that familiar with the tools and had no success as well.

Could someone more familiar with cutting text assist me please. Thank you in advance.

  • take a look at http://stackoverflow.com/questions/12934699/selecting-fields-from-json-output – LMC Feb 23 '17 at 23:25

1 Answers1

0

You can use jq to parse json :

curl https://api.cloudflare.com/client/v4/zones/xxxx/settings | \
    jq '.result | map({(.id):.value}) | add'

It gives :

{
  "always_online": "on",
  "server_side_exclude": "on",
  "sha1_support": "off",
  "sort_query_string_for_cache": "off",
  "ssl": "flexible"
}

If you want to extract the value of one field, for server_side_exclude :

curl https://api.cloudflare.com/client/v4/zones/xxxx/settings | \
    jq -r '.result | map({(.id):.value}) | add | .server_side_exclude'

The input I used for the parsing is here

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • Amazing ! Thank you mate, I have been testing around with **jq** for the past hour and a half and could not figure out the correct syntax. Thank you so much, this completely solves my issue. – Angel Asenov Feb 24 '17 at 00:40