How to extract json data from variables other than $response?


#1

I’ve asked this in another post, but not sure if it’s not been noticed as this is a specific question.

I have device data I can query from my sonos, which appears to be json formatted. However I can not access it in the same way as you would from the $response variable. ie variable.item

Am I missing something, or is $response a special case?

https://community.webcore.co/uploads/default/original/3X/5/9/5984422b526bedf3cc2fffca43c314fa85ce80b7.png


#2

Are you doing an API call to your device before attempting to parse the JSON?


#3

Not sure if you missed the edit, I’ve just added the test piston.

It just performs a refresh to ensure the data is up to date. I’m not sure if that necessary.
Then it just reads the data from the device attributes and I try to pick the uri item from the json returned.


#4

I don’t have a Sonos, so I may be of very little help here. I have to do an API call to my audio device (Kodi on a rPi) to get $response info. A quick google search does list an API for sonos. But I think I am missing the point of your question here.


#5

The sonos is just background on what I’m doing - trying to code round the fact it wont speak text and resume.

The issue is with trying to extract the uri variable from the json string data in the example piston.
If the same data had been returned into $response, I could use $response.uri, but data.uri des not work.
Either

  • $ response is a special case
  • data is not correctly formatted json
  • I’m missing something!

#6

I’ve just found this

@ipaterson

Sep '18

You will need to use a backslash \ to escape all {}\ characters in the JSON. Since all strings in webCoRE support { variableName } interpolated values it ends up trying to handle your JSON as if it were a webCoRE expression.

For example, { "response": { "version": "0.1" } } will need to be written as \{ "response": \{ "version": "0.1" \} \} . Then you should be able to use the Parse JSON string action and interact with the data via the $json system variable (e.g. $json.response.version ).

I’m not sure how to use the parse JSON string action? I’ve set up a test string (using { } as stated) Theres a json string command. I’ve had a play around, but don’t seem to get any values in $json.


#8

I had to do the same thing to my JSON strings for my API call.


#9

dynamic foo;

foo = parseJson(data)

Or

you can also try

you might want to make your ‘data’ variable type dynamic


#10

Thanks for the help. I think I’ve got it working. See example below for anyone else arriving here.