1

HI ,

 var jsonObj = [] ;

for (var i = 0; i < data.jobs.length; i++) {

            jsonObj.push({id: data.jobs[i].Dater, optionValue: data.jobs[i].INCPU});
        }

alert(jsonObj);

I am getting as result as

[object Object],[object Object],[object Object]
2

3 Answers 3

1

That is because you are alerting an array. Trying alerting an individual index of that array.

alert(jsonObj[0])
Sign up to request clarification or add additional context in comments.

2 Comments

which will output [object Object] ? :D
alert(jsonObj[0]) , this is outputing [object Object]
1

If you want to produce a JSON serialisation, use a JSON parser library like json2.js.

The serialised form will also produce the expected result when you pass it to alert().

9 Comments

@Marcelo This answer implies that JSON serialization can only be achieved with a separate library. This is of course not true, since all current browsers implement the JSON global object.
@Šime: That depends on what you define as current. If you want to support IE7, which still has about 10% of the market, then you'll run into trouble. Also, json2.js automatically falls back on the built-in JSON object, if present, so there is very little to be gained by avoiding it.
@Marcelo Let me repeat myself. Your answer implies that JSON serialization can only be achieved with a separate library. "If you want feature X, add library Y to your web-page" implies that library Y (or a similar library) is required for feature X. A more correct answer would be: "If you want feature X, use function Y" (JSON.stringify() in this case), and then "Note: some older browsers (IE6, IE7, FF3 - ~20% of the market) don't implement this function. If you need to support those browsers, add library Z to your web-page".
@Šime: There was no need to repeat yourself; I understood you perfectly well the first time. In fact, it appears that it is you who failed to properly read what I wrote. My response to your comment was to the effect that, if you define IE7 as "current" — which I do, since 10% is still a very important segment of the market for most serious websites — then your claim that, "This is of course not true," is patently false. Moreover, you'll note that I never actually repudiated your first sentence.
If you really want to split hairs, my answer was either correct or it wasn't. If you can't point to anything I said that was false, then any talk of a "more correct" answer is dubious. My first statement was merely advice, which you can disagree with, but I note that in your suggested amended, you didn't suggest any change to the wording, merely an appended qualifier.
|
0

I believe you're trying to achieve this:

var obj = [];

// populate obj in a loop

var jsonStr = JSON.stringify(obj);

alert(jsonStr);

Live demo: http://jsfiddle.net/simevidas/Smd2P/1/

Comments