0

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?

`

3 Answers 3

3

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
})
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.