AlessioDionisi AlessioDionisi - 2 months ago 18
JSON Question

JSON array of strings foreach

Example JSON:

{
"name": "Size",
"options": [
"S",
"M",
"L"
]
}


I do not understand why
options
is parsed as a string like
SML
and foreach does not work

SOLVED:

Instead of doing a foreach I used a for

const jsonData = '{"name": "Size","options": ["S","M","L"]}'
const data = JSON.parse(jsonData)

// Foreach not be used in array of strings, this was the error
//data.options.forEach((option) => {
//
//})

// For works fine
for (const i = 0; i < data.options.length; i++) {
const option = data.options[i]
}

rsp rsp
Answer

It seems to work fine:

var json = `{
  "name": "Size",
  "options": [
    "S",
    "M",
    "L"
  ]
}`;

var obj = JSON.parse(json);
console.log(obj.options);

See DEMO.

You don't show how you parse it, how you access the obj.options array, what you get and what you expect. It's impossible to tell you what's wrong with your code that you don't show. The JSON is fine and I showed you the correct way to parse it that works as expected.