ilhan
ilhan

Reputation: 8952

Converting an object/array into JSON?

I have an array (it might be an object too, I don't know what I'm talking about):

grid.columns[0].text
grid.columns[1].text
grid.columns[2].text

And so on. I want to convert it into JSON. I've tried to use JSON.stringify(grid.columns.text) but it didn't work: it gives null.

Upvotes: 2

Views: 1285

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

Try with

JSON.stringify(grid.columns.map(function(item) {
    return item.text;
}));
// ["value of text 0", "value of text 1",...]

Alternatively

JSON.stringify(grid.columns.map(function(item) {
    return {text:item.text};
}));
// [{"text":"value of text 0"},{"text":"value of text 1"},..]

Upvotes: 3

Ben Rowe
Ben Rowe

Reputation: 28711

Using JSON.stringify(grid.columns.text) isn't going to work based off your provided structure:

Try the following instead:

JSON.stringify(grid.columns);

This should produce something like:

[
  {"text": "value"},
  {"text": "value2"},
  {"text": "value3"},
  ...
]

Upvotes: 1

Related Questions