简体   繁体   中英

How to parse json from the specific array string to array object?

JSON object:

{
    "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. want to convert/parse as Array as it is..

Normally it should return in json object like below.

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:

 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.

the quotation marks around the list make JSON.parse treat it like a string, as it really is a string.

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. eg

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

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