Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  95] [ 1]  / answers: 1 / hits: 34772  / 11 Years ago, tue, december 10, 2013, 12:00:00

I have PHP outputting a JSON multidimensional array as follows:



{rates:[{meter:30,rate:0.15060,ppd:10.000}]}


However, I keep getting an error when trying to decode it on the JavaSCript side of things.



Uncaught TypeError: Cannot read property 'length' of null


Here is the code below for the jQuery side of things:



success: function (result) {
console.log(result);
$.each($.parseJSON(result), function (item, value) {
if (item == rates) {
$.each($.parseJSON(value), function (i, object) {
console.log(i + = + object);
});
}


The 1st console log gives me the output I mentioned at the top, but for some reason i am not able to access the array as I thought I would.



Any help is greatly appreciated :)


More From » jquery

 Answers
5

You don't need to call parseJSON again on value. It's already an object



var result='{rates:[{meter:30,rate:0.15060,ppd:10.000}]}';
console.log(result);
$.each($.parseJSON(result), function (item, value) {
if (item == rates) {
$.each(value, function (i, object) {
$.each(object, function (subI, subObject) {
console.log(subI + = + subObject);
});
});

}
});


Also, incase you were wondering the error was happening because you were trying to call parseJSON on an object and parseJSON expects a string so it was returning null to the each function which was then trying to do a for loop based on null.length


[#73829] Sunday, December 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
;