-2

I need to get values from a JSONString using javaScript. I did the following :

jsonData = JSON.stringify(data);
var jsonVar = "jVar";


for (var l = 0; l < jsonData.jsonVar.length; l++) {
                    var item = jsonData.itemI+"-"+itemJ+"-"+itemK.split(' ').join('')[i];
                    alert(cuecard);
                }

Here is the JSONData:

{"jVar":["123","234"]}

But i am getting the following exception:

Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (test.jsp:62)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)

I saw the example in here and i dont know the mistake i am doing.Can any one please suggest.

user3750720
  • 163
  • 1
  • 13

4 Answers4

2

You have it the wrong way round - JSON.stringify turns a javascript object to a string. And JSON.parse parses a JSON String to a javascript object.

Also, having done that, if you want to read a property using a string use square bracket notation:

var jsonData = JSON.parse(data);
var jsonVar = "jVar";

for (var l = 0; l < jsonData[jsonVar].length; l++) {
  var arrayItem = jsonData[jsonVar][l];
 ...
}

(As an aside l is a bad choice for a loop control variable - looks too much like a 1)

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

You have to access the proprty like this.

for (var l = 0; l < jsonData[jVar].length; l++) {

}
Himan
  • 379
  • 1
  • 7
0

Make sure you have a valid JSON object first. I don't think what you have is valid to start with.

JSON.parse(yourValidJsonObject);

The above should give you a plain Javascript object you can work with.

Whereas, JSON.stringify(yourPlainJavascriptObject) will turn the plain js object to a JSON object.

pro
  • 792
  • 7
  • 30
-1

Simply run JSON.parse(jsonString) to get an object from it

Shardj
  • 1,800
  • 2
  • 17
  • 43