Reputation: 9545
what is the difference in the following between the result of p
and q
and why would you do either way, which is best?
var my = [
{"a":"sdsds"},
{"b":"sdsds"},
{"c":"sdsds"},
{"d":"sdsds"},
{"e":"sdsds"}
];
var p = JSON.stringify({ "myText": my };);
var q = { "myText": JSON.stringify(my) };
Upvotes: 0
Views: 127
Reputation: 943220
One creates a JSON text consisting of an object with the property 'myText' with the value being the data that 'my' contains (i.e. an array of objects each of which has one property/string pair).
The other creates an object consisting of a property 'myText' with the value being a string containing a JSON text built from the data in 'my'.
why would you do either way
The former is generally the approach taken when creating JSON.
That latter might be useful if you planned to pass the object to something like jQuery's data
property in an .ajax()
call.
which is best
Neither. They simply different. "Best" is whatever works for what you are going to do with the variables.
Upvotes: 3
Reputation: 224905
p
is a string containing:
'{"myText":[{"a":"sdsds"},{"b":"sdsds"},{"c":"sdsds"},{"d":"sdsds"},{"e":"sdsds"}]}'
q
is an object:
{
myText: '[{"a":"sdsds"},{"b":"sdsds"},{"c":"sdsds"},{"d":"sdsds"},{"e":"sdsds"}]'
}
They're not the same thing, so I can't tell you which is best. What do you want to use it for?
Upvotes: 8
Reputation: 887365
p
is a string that looks like "{ \"mytext\": ... }"
.
q
is an object with a property called mytext
.
Upvotes: 3