I’ve been struggling with how to retrieve data from a JSON structured response to a query of a Sony Bravia TV. I’ve tried SEVERAL syntax variations to get just a single element’s data, but no joy.
The response is sent to a textarea field having the id "log". Here is what gets displayed:
{
"result": [
[
{
"target": "speaker",
"volume": 22,
"mute": false,
"maxVolume": 100,
"minVolume": 0
}
]
],
"id": 1
}
The javascript function is below. In the last line, I’m trying to see a single element, but get nothing. What should the last line be?
var gblJSONresponse = [];
function send(service, method, params) {
var ip = 'xxx.xxx.xxx.xxx';
var psk = 'xxxx';
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var resp = xhr.responseText;
gblJSONresponse = JSON.parse(xhr.response);
log(JSON.stringify(JSON.parse(xhr.response), null, ' '));
};
xhr.open('POST', 'http://' + ip + '/sony/' + service);
if (psk) {
xhr.setRequestHeader('X-Auth-PSK', psk);
}
xhr.send(JSON.stringify({
method: method,
version: '1.0',
id: 1,
params: params ? [params] : [],
}));
window.alert("JSONresponse:n"+JSONresponse[0].result[0].target);
}
2
Answers
I've gotten it to work by placing the alert inside the xhr.onload function. The line is: window.alert("JSONresponse:n"+gblJSONresponse.result[0][0].target);
I think you are parsing response instead of responseText
Check responseType if set to json or text , if its set to text look into responseText otherwise it will appear in response
From Mozilla web docs here