Javascript 将字符串转换为对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16213864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:44:51  来源:igfitidea点击:

Javascript Convert String to Array of Objects

javascriptjsonnode.jsparsingmalformed

提问by nelsonic

I have a NodeJS App that accepts a a string (uploaded input!) I have No Controlover the input I am merely building a REST Service to Processesthe data.

我有一个接受字符串的 NodeJS 应用程序(上传的输入!)我无法控制输入我只是构建一个 REST 服务来处理数据。

That string is meantto be an Arrayof JSON Objectsthat I can then loop through to extract each element ...

该字符串的意思是一个阵列JSON对象,我可以然后依次通过以提取各要素...

I'm receivingthe following (as a string):

收到以下内容(作为字符串):

[
  {Name: 'Jane',
       Id: '005b0000000MGa7AAG'},
  {Name: 'Tom',
       Id: '005b0000000MGa7AAF'}
]

When I try to JSON.parsethis I get

当我尝试JSON.parse 时,我得到

SyntaxError: Unexpected token N

Understandably so, because I knowthis is Invalid JSON

可以理解,因为我知道这是无效的 JSON

whereas Thisnext string is valid JSONand passes http://jsonlint.com/:

接下来的字符串是有效的JSON并将http://jsonlint.com/

[
    {"Name": "Hyman",
        "Id": "005b0000000MGa7AAA"},
    {"Name": "Jill",
        "Id": "005b0000000MGa7AAB"}
]

My question is: Howcan I accept the firstinput and parse it to allow:

我的问题是:我怎样才能接受第一个输入并解析它以允许:

parsed[0]['Name'] == 'Jane'
>> true

My first instinct is to string replace the keys (e.g. Name to "Name") and then try parsing it. But if anyone else has a solution, I'd be grateful.

我的第一直觉是用字符串替换键(例如 Name 到“Name”),然后尝试解析它。但如果其他人有解决方案,我将不胜感激。

回答by musefan

You can do this with a bit of Regex replacing:

你可以用一些 Regex 替换来做到这一点:

var json = "[ {Name: 'Jane', Id: '005b0000000MGa7AAG'}, {Name: 'Tom', Id: '005b0000000MGa7AAF'} ]";

var newJson = json.replace(/([a-zA-Z0-9]+?):/g, '"":');
newJson = newJson.replace(/'/g, '"');

var data = JSON.parse(newJson);

alert(data[0]["Name"]);

First of all we wrap the propertie names with quotes, then we replace the single-quotes with double-quotes. This is enough to make it valid JSON which can then be parsed.

首先,我们用引号将属性名称括起来,然后用双引号替换单引号。这足以使它成为有效的 JSON,然后可以对其进行解析。

Here is a working example

这是一个工作示例



NOTE: Using RegEx in general for things like this is not ideal, and this solution will only work under specific circumstances (like this example). As mentioned in comments, one problem would be if the data values contained a colon :

注意:一般情况下,将 RegEx 用于此类事情并不理想,并且此解决方案仅适用于特定情况(如本例)。正如评论中提到的,一个问题是数据值是否包含冒号:

With that in mind, this is a more reliable solution:

考虑到这一点,这是一个更可靠的解决方案:

var json = $("div").html();

var newJson = json.replace(/'/g, '"');

newJson = newJson.replace(/([^"]+)|("[^"]+")/g, function(##代码##, , ) {
    if () {
        return .replace(/([a-zA-Z0-9]+?):/g, '"":');
    } else {
        return ; 
    } 
});

var data = JSON.parse(newJson);
alert(data[0]["Name"]);

This will match any variables (alphanumeric) that end with a colon :, but will ingore any matches that are found between quotes (i.e. data string values)

这将匹配以冒号结尾的任何变量(字母数字):,但将忽略在引号之间找到的任何匹配(即数据字符串值)

Here is an example

这是一个例子

回答by Maximiliano Becerra

Create a javascript class, populate the object with your input and then convert it in a clean json using: JSON.stringify(object)to avoid errors . My full post here.

创建一个 javascript 类,使用您的输入填充对象,然后使用以下命令将其转换为干净的 json:JSON.stringify(object)以避免错误。我的完整帖子在这里

NOTE: if you use IE7 or less version you must add the JSON.jslibrary to use JSON.stringify()function.

注意:如果您使用 IE7 或更低版本,则必须添加JSON.js库才能使用JSON.stringify()功能。