简体   繁体   中英

Converting associative array string to array

I've been trying to convert an associative array string but I can't seem to make it work.

I've tried the code below but it is not working.

var string = "{'custom_text_record': 'Text Here', 'fill_record': '0'}";
var s_obj = JSON.parse(string) ;

alert(s_obj['custom_text_record']);

You need to basically get JSON format from the associative array string,

The JSON format should be "{'custom_text_record': 'TextHere','fill_record':'0'}" before we use JSON parse function

Please try this.

 var string = '{"custom_text_record": "Text Here", "fill_record": "0"}'; var jsonStrig = '{'; var items = string.split(','); for (var i = 0; i < items.length; i++) { var current = items[i].split(':'); jsonStrig += '"' + current[0].replace(/{|'|"|}|\s/g, '') + '":"' + current[1].replace(/{|'|"|}|\s/g, '') + '",'; } jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1); jsonStrig += '}'; var s_obj = JSON.parse(jsonStrig); console.log(s_obj['custom_text_record']);

Regex might be used to filter the single quote, double quote, and bracket, spaces which can appear in the associative array string. I think we can convert any type of associative array string like '{ key: value }' style into the correct JSON format and finally get an array in this way. I hope this would be helpful.

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