简体   繁体   English

如何将json从特定的数组字符串解析为数组对象?

[英]How to parse json from the specific array string to array object?

JSON object: JSON对象:

{
    "data": {
        "myStatus": "[1 2 21 0 50 0 0 0],[2 1 3 1 50 0 0 0]"
    },
    "success": true
}

When we converting to the json object, it returning the myStatus is just string. 当我们转换为json对象时,它返回的myStatus只是字符串。 want to convert/parse as Array as it is.. 想要按原样转换/解析为数组。

Normally it should return in json object like below. 通常,它应返回json对象,如下所示。

var jsonObj= JSON.parse(<abovestring>);
jsonObj.data.myStatus[0] => [1 2 21 0 50 0 0 0];
jsonObj.data.myStatus[0][0] => 1
jsonObj.data.myStatus[0][1] => 2
jsonObj.data.myStatus[0][2] => 21

Is it possible to split like this? 有可能这样分裂吗?

You could use String#split along with Array#map to do this: 您可以结合使用String#splitArray#map来执行此操作:

 let str = "[1 2 21 0 50 0 0 0],[2 1 3 1 50 0 0 0]"; let arr = str .split(',') .map(item => item.slice(1, -1)) .map(item => item.split(' ')); console.log(arr); 

But this is very dirty approach, and is prone to bugs if the string format changes. 但这是一种非常肮脏的方法,并且如果字符串格式发生更改,则容易出现错误。 You should instead try to fix your JSON format. 相反,您应该尝试修复JSON格式。

the quotation marks around the list make JSON.parse treat it like a string, as it really is a string. 列表周围的引号使JSON.parse像字符串一样对待它,因为它实际上是一个字符串。

try either changing it to a valid array by removing the quotation marks, adding [] square brackets around the array, and adding , commas between elements , eg: 尝试通过除去引号其更改为一个有效的数组,加入[]阵列周围方括号中,并添加,元件之间,例如逗号:

{
    "data": {
        "myStatus": [[1, 2, 21, 0, 50, 0, 0, 0], [2, 1, 3, 1, 50, 0, 0, 0]]
    },
    "success": true
}

if u have no control over your json string and it must contain a string for data.myStatus , then you'd need an additional step to parse it manually. 如果您无法控制您的json字符串,并且其中必须包含data.myStatus的字符串,那么您将需要一个额外的步骤来手动解析它。 eg 例如

var string = jsonObj.data.myStatus;
string = `[${string}]`;
string = string.replace(/ +/g, ',');
jsonObj.data.myStatus = JSON.parse(string);

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

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