3

I´m trying to parse some JSON, which is the output of the Philips Hue API.

I found the tool jsawk, but somehow I´m not able to access the data inside the JSON Object.

The command:

... | jsawk 'return this.f709f9c0b-on-0.name'

works but unfortunately I don't have the ID of each object (e.g. f709f9c0b-on-0). Is there a way to access the object without knowing the ID and then to find out that ID. I tried to use "*" or Iterations of the objects but nothing was working.

Thanks in advance

The output looks like this:

{
    "f709f9c0b-on-0": {
        "name": "Badezimmer on 0",
        "lights": [
            "4"
        ],
        "owner": "3e281978544fb15b42bc0e3a3f4ce3",
        "recycle": true,
        "locked": false,
        "appdata": {},
        "picture": "",
        "lastupdated": "2016-02-17T17:20:06",
        "version": 1
    },
    "69d313be0-on-0": {
        "name": "Klavier on 0",
        "lights": [
            "1"
        ],
        "owner": "3e281978544fb15b42bc0e3a3f4ce3",
        "recycle": true,
        "locked": false,
        "appdata": {},
        "picture": "",
        "lastupdated": "2016-02-17T17:31:05",
        "version": 1
    },
...
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Marcel
  • 43
  • 6

2 Answers2

0

f709f9c0b-on-0 is not a valid identifier due to the hyphens, so you can't use the dot notation. This might work (untested)

... | jsawk 'return this["f709f9c0b-on-0"].name'

I don't have jsawk, but can do it like this:

... | jq '.["f709f9c0b-on-0"].name'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks or the answer. Actually the dot notation works. My Problem ist, that I don´t have the ID. I need some kind of variable for "f709f9c0b-on-0". The ID´s is random generated, so I can't reproduce that. I need something that iterates through all JSON objects. Is that possible? – Marcel Feb 25 '16 at 06:58
  • You'll probably need to use something like `forEach(this.keys(), ...)` – glenn jackman Feb 25 '16 at 22:05
0

Just for the rest of the world. I solved the problem, by creating a .jar, which handles the problem. I find it much easier to do this in Java, than in bash.

I used this JSON-classes: https://github.com/stleary/JSON-java Just download the files, create the package org.json and your good to go.

The Java Code, which worked for me is:

String JSON = "your JSON";
JSONObject jsonObject = new JSONObject(JSON);
    ArrayList<ArrayList<String>> keyArray = new ArrayList<>();
    Iterator<String> keys = jsonObject.keys(); //get all JSON keys

    while (keys.hasNext()) { //for all keys do...
        String key = (String) keys.next(); //get Current Key
       //Now you can access the Object in the Object with: 
jsonObject.getJSONObject(key).getString("name")
    }

I hope this helps someone.

Marcel
  • 43
  • 6