最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't parse JSON response - Stack Overflow

programmeradmin4浏览0评论

I'm trying to parse the following JSON response:

{
  "AgApplyTableE*!": [
    {
      "Index": 1,
      "StringVal": "Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done.  Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"
    }
  ]
}

Here's my code:

$('#applyfailreason').click(function (){    
  var t = $(this);
  var DeviceName = $('.DeviceName').val();
  var Username = $('.Username').val();
  var Password = $('.Password').val();

  $.ajax({
    method: 'GET',
    url: 'http://' + DeviceName + '/config/AgApplyTable',
    headers: {
      "Authorization": "Basic " + btoa('' + Username + '' + ":" + '' + Password + '')
    },
    dataType: 'json',
    contentType: 'application/json',
    success: function(data) {
      var test = JSON.stringify(data);
      console.log(test);
    },
    statusCode: {
      406 : function() {
        alert('There is an unexpected string in your data.\nFix the error and try again.');
      },
      401 : function() {
        alert('Wrong username or password.');
      }
    },
  });                   
});

I get the following on the console (which is ok):

{"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done.  Use 'diff' to see pending changes,U+0085       then use configuration menus to correct errors.U+0085"}]}

But I want to print only the "StringVal" out of the JSON response. Tried:

var test2 = JSON.stringify(data.StringVal);
console.log(test2);

Gives:

undefined

I also tried the following (with dataType: 'jsonp',):

var test4 = JSON.parse(data.StringVal);

But then Chrome sends a GET request to a strange URI (which actually gives 200OK):

config/AgApplyTable?callback=jQuery111306132095118518919_1436256387242&_=1436256387244

And I get the following error:

Uncaught SyntaxError: Unexpected token :

Any idea how to print to console only "StringVal" out of the JSON response?

Thanks.

I'm trying to parse the following JSON response:

{
  "AgApplyTableE*!": [
    {
      "Index": 1,
      "StringVal": "Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done.  Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"
    }
  ]
}

Here's my code:

$('#applyfailreason').click(function (){    
  var t = $(this);
  var DeviceName = $('.DeviceName').val();
  var Username = $('.Username').val();
  var Password = $('.Password').val();

  $.ajax({
    method: 'GET',
    url: 'http://' + DeviceName + '/config/AgApplyTable',
    headers: {
      "Authorization": "Basic " + btoa('' + Username + '' + ":" + '' + Password + '')
    },
    dataType: 'json',
    contentType: 'application/json',
    success: function(data) {
      var test = JSON.stringify(data);
      console.log(test);
    },
    statusCode: {
      406 : function() {
        alert('There is an unexpected string in your data.\nFix the error and try again.');
      },
      401 : function() {
        alert('Wrong username or password.');
      }
    },
  });                   
});

I get the following on the console (which is ok):

{"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done.  Use 'diff' to see pending changes,U+0085       then use configuration menus to correct errors.U+0085"}]}

But I want to print only the "StringVal" out of the JSON response. Tried:

var test2 = JSON.stringify(data.StringVal);
console.log(test2);

Gives:

undefined

I also tried the following (with dataType: 'jsonp',):

var test4 = JSON.parse(data.StringVal);

But then Chrome sends a GET request to a strange URI (which actually gives 200OK):

config/AgApplyTable?callback=jQuery111306132095118518919_1436256387242&_=1436256387244

And I get the following error:

Uncaught SyntaxError: Unexpected token :

Any idea how to print to console only "StringVal" out of the JSON response?

Thanks.

Share Improve this question edited Jul 7, 2015 at 8:20 Achrome 7,82114 gold badges38 silver badges45 bronze badges asked Jul 7, 2015 at 8:15 Udi DahanUdi Dahan 5021 gold badge6 silver badges11 bronze badges 2
  • var test4 = JSON.parse(data.AgApplyTableE*![0][StringVal]); – PHP Worm... Commented Jul 7, 2015 at 8:20
  • Have you tried this var test2 = JSON.stringify(data["AgApplyTableE*!"][0].StringVal); – Jai Commented Jul 7, 2015 at 8:23
Add a ment  | 

5 Answers 5

Reset to default 2

Your response is an object containing one property named "AgApplyTableE*!", which is an array that contains one element, which is an object that contains the property "StringVal".

So you'd have to access it by data["AgApplyTableE*!"][0].StringVal.

Use console.log(data['AgApplyTableE*!'][0].StringVal)

In your response, there is no such thing as StringVal as direct suboridnate of data. The property StringVal is inside the internal object AgApplyTableE*! therefore data.StringVal is undefined.

Also, another problem I see here is that you're stringifying the response and then trying to access the property StringVal. If you stringify, you test variable will be a string and string doesnt have a property StringVal (unless you set that in your proto)

EDIT: Added missing [0] index.

Try

var test2 = data["AgApplyTableE*!"][0].StringVal;
console.log(test2);
test ={"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done.  Use 'diff' to see pending changes,U+0085       then use configuration menus to correct errors.U+0085"}]};

console.log(test["AgApplyTableE*!"][0]["StringVal"]);

Demo

I think that is because you have two levels here, not only one. In order to get that value out, you probably would need something like

var test2 = JSON.parse(data);
console.log(test2["AgApplyTableE*!"][0].StringVal);

Altough I'm not sure AgApplyTableE*! is a really good identifier here. Probably you can change something else, and then you can also use . notation to reach the members.

发布评论

评论列表(0)

  1. 暂无评论