简体   繁体   English

将字符串转换为嵌套数组

[英]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. 我有一个从服务器传递来的字符串,该字符串被AJAX调用,我必须将该字符串转换为一个嵌套数组,该数组将用于填充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: 我需要将其转换为JavaScript中的数组,如下所示:

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 . 正如评论中指出的那样,最好的解决方案是从服务器返回有效的JSON并使用JSON.parse进行解析。
You can use tools like https://jsonlint.com/ or JSV to check that your JSON is valid. 您可以使用https://jsonlint.com/JSV之类的工具来检查JSON是否有效。

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 . 如果由于某些“现实世界的问题”而导致您的服务器不是JSON投诉,则可以使用dirty-json之类的肮脏解析器,也可以编写自己的JSON parse

dirty-json does not require object keys to be quoted, and can handle single-quoted value strings. dirty-json不需要引用对象键,并且可以处理单引号的值字符串。

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

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 通过稍微改变从服务器返回字符串的方式,您可以JSON.parse

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. 使用eval()方法评估给定代码的完成值。 If the completion value is empty, undefined is returned: 如果完成值为空,则返回undefined:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM