简体   繁体   English

将关联数组字符串转换为数组

[英]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,您基本上需要从关联数组字符串中获取JSON 格式

The JSON format should be "{'custom_text_record': 'TextHere','fill_record':'0'}" before we use JSON parse function JSON 格式应该是 "{'custom_text_record': 'TextHere','fill_record':'0'}" 在我们使用JSON 解析ZC1C425268E68385D1AB507ZAF8Z 之前

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.我认为我们可以将任何类型的关联数组字符串(例如'{ key: value }' 样式)转换为正确的JSON 格式,最终以这种方式得到一个数组 I hope this would be helpful.我希望这会有所帮助。

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

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