简体   繁体   中英

Convert string to nested array

I have a string passed from server which was called with AJAX and I have to convert the string into a nested array which will be used to populate on PDF.

For example:

var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";

and I need to convert into an array in JavaScript which will be like this:

var newTableData = [
    { name: 'Bartek', age: 34 },
    { name: 'John', age: 27 },
    { name: 'Elizabeth', age: 30 }
];

How can I do that?

As pointed out in the comments, the best solution would be to return a valid JSON from the server and to parse it using JSON.parse .
You can use tools like https://jsonlint.com/ or JSV to check that your JSON is valid.

If because of some "real world problem", your servers aren't JSON complaint, you can use a dirty parser like dirty-json or write your own JSON parse .

dirty-json does not require object keys to be quoted, and can handle single-quoted value strings.

var dJSON = require('dirty-json');
dJSON.parse("{ test: 'this is a test'}").then(function (r) {
    console.log(JSON.stringify(r));
});

// output: {"test":"this is a test"}

Your last resort, while technically possible and the easiest to implement, is probably your worst choice because of it's dangers . but it would work out of the box: eval .

eval(tableData);
// [ { name: 'Bartek', age: 34 },
//   { name: 'John', age: 27 },
//   { name: 'Elizabeth', age: 30 } ]

By slightly changing how you return the string from the server you can JSON.parse it

var dataString = '[{"name":"Bartek","age":34},{"name":"John","age":27},{"name":"Elizabeth","age":30}]';
var data = JSON.parse(dataString);
console.log(data);

Use eval() method The completion value of evaluating the given code. If the completion value is empty, undefined is returned:

 var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]"; tableData = eval(tableData); console.log(tableData[0]); 

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