我有以下JSON:
{
"apps": {
"1C-Bitrix": {
"cats": [
1
],
"headers": {
"Set-Cookie": "BITRIX_",
"X-Powered-CMS": "Bitrix Site Manager"
},
"html": "(?:<link[^>]+components/bitrix|(?:src|href)=\"/bitrix/(?:js|templates))",
"implies": "PHP",
"script": "1c-bitrix",
"website": "www.1c-bitrix.ru",
"icon": "1C-Bitrix.png"
},
"1und1": {
"cats": [
6
],
"implies": "PHP",
"url": "/shop/catalog/browse\\?sessid=",
"website": "1und1.de",
"icon": "1und1.png"
}
}
我想把它变成一个Javascript对象,在正则表达式语句中删除键上的双引号和双重转义。
有没有办法做到这一点,我一直在努力与节点和JSON.stringify,我只是无法获得有效的输出。
我想这样做的原因是我有这个脚本:
(function() {
//'use strict';
if ( wappalyzer == null ) return;
var w = wappalyzer;
w.apps = {
'1C-Bitrix': {
cats: [ 1 ],
headers: { 'X-Powered-CMS': /Bitrix Site Manager/, 'Set-Cookie': /BITRIX_/i },
html: /<link[^>]+components\/bitrix|(src|href)=("|')\/bitrix\/(js|templates)/i,
script: /1c\-bitrix/i,
implies: [ 'PHP' ]
},
'1und1': {
cats: [ 6 ],
url: /\/shop\/catalog\/browse\?sessid\=/,
implies: [ 'PHP' ]
}
};
})();
它需要一个Javascript对象(w.apps)
如果我用这样的JSON替换它会失败:
(function() {
//'use strict';
if ( wappalyzer == null ) return;
var w = wappalyzer;
w.apps = {
"1C-Bitrix": {
"cats": [
1
],
"headers": {
"Set-Cookie": "BITRIX_",
"X-Powered-CMS": "Bitrix Site Manager"
},
"html": "(?:<link[^>]+components/bitrix|(?:src|href)=\"/bitrix/(?:js|templates))",
"implies": "PHP",
"script": "1c-bitrix",
"website": "www.1c-bitrix.ru",
"icon": "1C-Bitrix.png"
},
"1und1": {
"cats": [
6
],
"implies": "PHP",
"url": "/shop/catalog/browse\\?sessid=",
"website": "1und1.de",
"icon": "1und1.png"
}
};
})();
答案 0 :(得分:1)
您只需在JavaScript中插入此对象,它就会正确解释它:
var obj = {
"apps": {
"1C-Bitrix": {
"cats": [
1
],
"headers": {
"Set-Cookie": "BITRIX_",
"X-Powered-CMS": "Bitrix Site Manager"
},
"html": "(?:<link[^>]+components/bitrix|(?:src|href)=\"/bitrix/(?:js|templates))",
"implies": "PHP",
"script": "1c-bitrix",
"website": "www.1c-bitrix.ru",
"icon": "1C-Bitrix.png"
},
"1und1": {
"cats": [
6
],
"implies": "PHP",
"url": "/shop/catalog/browse\\?sessid=",
"website": "1und1.de",
"icon": "1und1.png"
}
}
};
document.body.innerText = "See, no escaping: " + obj.apps['1und1'].url;
如果您将此JSON作为字符串接收(例如,作为AJAX调用的结果),则可以使用JSON.parse
将JSON字符串转换为对象:
var ajaxResult = "{ \"apps\": { \"1C-Bitrix\": { \"cats\": [ 1 ], \"headers\": { \"Set-Cookie\": \"BITRIX_\", \"X-Powered-CMS\": \"Bitrix Site Manager\" }, \"html\": \"(?:<link[^>]+components\/bitrix|(?:src|href)=\\\"\/bitrix\/(?:js|templates))\", \"implies\": \"PHP\", \"script\": \"1c-bitrix\", \"website\": \"www.1c-bitrix.ru\", \"icon\": \"1C-Bitrix.png\" }, \"1und1\": { \"cats\": [ 6 ], \"implies\": \"PHP\", \"url\": \"\/shop\/catalog\/browse\\\\?sessid=\", \"website\": \"1und1.de\", \"icon\": \"1und1.png\" } } }";
var obj = JSON.parse(ajaxResult);
document.body.innerText = "See, no escaping: " + obj.apps['1und1'].url;