简体   繁体   中英

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 .

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"},..]

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"},
  ...
]

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