简体   繁体   中英

what is the difference here in this use of JSON.stringify()?

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) };

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?

p is a string that looks like "{ \\"mytext\\": ... }" .

q is an object with a property called mytext .

One creates a JSON text consisting of an object with the property 'myText' with the value being the data that 'my' contains (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM