简体   繁体   中英

Building JSON-Object with inner array in Javascript

I need this string:

{"name":"ne","type":"Choice","id":"ne","width":150,"items":[{"id":"test1","value":"test1","title":"test1"},{"id":"test3","value":"test3","title":"test3"},{"id":"test2","value":"test2","title":"test2"}]}

I have the following:

JSON.stringify(itemList) gives me this:

[{"id":"test1","value":"test1","title":"test1"},{"id":"test3","value":"test3","title":"test3"},{"id":"test2","value":"test2","title":"test2"}]

I tried this:

JSON.stringify({
      name: loadName(),
      type: "Choice",
      id: complexTableId,
      width: loadWidth(),
      items: JSON.stringify(itemList)
})

But I get this:

{"name":"ne","type":"Choice","id":"ne","width":"150","items":"[{\\"id\\":\\"test1\\",\\"value\\":\\"test1\\",\\"title\\":\\"test1\\"},{\\"id\\":\\"test3\\",\\"value\\":\\"test3\\",\\"title\\":\\"test3\\"},{\\"id\\":\\"test2\\",\\"value\\":\\"test2\\",\\"title\\":\\"test2\\"}]"}

Does anyone know, where my mistake lies?

`

no need to call JSON.stringify on your items before stringifying everything, try this :

JSON.stringify({
    name: loadName(),
    type: "Choice",
    id: complexTableId,
    width: loadWidth(),
    items: itemList
})

You are calling JSON.stringify on itemList twice. This will cause your stringified object to be stringified again.

Notice the two backslash + double quote ( \\" ) in the double stringify example below:

// single stringify
> JSON.stringify({ test: "Hello World" });
< "{"test":"Hello World"}"

// double stringify
> JSON.stringify({ test: JSON.stringify("Hello World") });
< "{"test":"\"Hello World\""}"

If you want to properly stringify an object then only use JSON.stringify once on the whole object:

JSON.stringify({
    name: loadName(),
    type: "Choice",
    id: complexTableId,
    width: loadWidth(),
    items: itemList // don't include "JSON.stringify" here
});
JSON.stringify({
                    name: loadName(),
                    type: "Choice",
                    id: complexTableId,
                    width: loadWidth(),
                    items: itemList
                });

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