skip to Main Content

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


  1. Chosen as BEST ANSWER

    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);


  2. 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

    XMLHttpRequest.response Read only Returns an ArrayBuffer, a Blob, a
    Document, a JavaScript object, or a string, depending on the value of
    XMLHttpRequest.responseType, that contains the response entity body.

    XMLHttpRequest.responseText Read only Returns a string that contains
    the response to the request as text, or null if the request was
    unsuccessful or has not yet been sent.

    From Mozilla web docs here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search