我有这样的String
{Name: India, Path: test.png, Id: 1, Uri: /api/1}
我通过Javascript试图像这样解析该值
var sCountry = document.getElementById("countries").value; // this will give value as {Name: India, Path: test.png, Id: 1, Uri: /api/1}
var fixedJSON = sCountry
// Replace ":" with "@colon@" if it's between double-quotes
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '@colon@') + '"';
})
// Replace ":" with "@colon@" if it's between single-quotes
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '@colon@') + '"';
})
// Add double-quotes around any tokens before the remaining ":"
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
// Turn "@colon@" back into ":"
.replace(/@colon@/g, ':')
;
console.log('Before: ' + sCountry);
console.log('After: ' + fixedJSON);//Output comes like this {"Name": India, "Path": test.png, "Id": 1, "Uri": /api/1}
var obj = JSON.parse(fixedJSON);
它给出了这样的错误
unexpected token e in json at position 10 at json.parse
我猜输出应该是这样的
{"Name": "India" , "Path": "test.png", "Id": 1, "Uri": "/api/1"}
谁能帮助我解决此字符串到JSON的转换。这样我就可以解析并获取“ Id”的值
答案 0 :(得分:2)
尝试使用split and join:
我已列出了所需的每个步骤,但您可以将其缩小一些。
let val = '{"Name": India, "Path": test.png, "Id": 1, "Uri": /api/1}';
// Remove brackets from string (first and last char)
let valWithoutBrackets = val.substring(1, val.length-1);
// Make key value pair array in string format (delimited by : )
let keyValuePairStrings = valWithoutBrackets.split(",");
// Make two dimensional key value pair array
let keyValuePairs = keyValuePairStrings.map(k => k.split(":").map(kv => kv.trim()));
// Map all values to values with brackets, except Id
let keyValuePairsWithBrackets = keyValuePairs.map(k => {
if(k[0] != '"Id"') {
k[1] = `"${k[1]}"`;
}
return k;
});
// Make two dimensional key value pair array to key value string array
let resultKeyValuePairStrings = keyValuePairsWithBrackets.map(k => k.join(":"));
// Make key value string array to list of keyvalues and add brackets again
let resultString = `{${resultKeyValuePairStrings.join(",")}}`;
// Log the parsed JSON Id
let obj = JSON.parse(resultString);
console.log(obj);
console.log(obj.Id);
如果将这样的正则表达式直接添加到我的代码中,您还可以跳过正则表达式:
let val = '{Name: India, Path: test.png, Id: 1, Uri: /api/1}';
// Remove brackets from string (first and last char)
let valWithoutBrackets = val.substring(1, val.length-1);
// Make key value pair array in string format (delimited by : )
let keyValuePairStrings = valWithoutBrackets.split(",");
// Make two dimensional key value pair array
let keyValuePairs = keyValuePairStrings.map(k => k.split(":").map(kv => kv.trim()));
// Map all values to values with brackets, except Id
let keyValuePairsWithBrackets = keyValuePairs.map(k => {
if(k[0] != 'Id') {
k[1] = `"${k[1]}"`;
}
k[0] = `"${k[0]}"`; // <-- Also put the key under quotations
return k;
});
// Make two dimensional key value pair array to key value string array
let resultKeyValuePairStrings = keyValuePairsWithBrackets.map(k => k.join(":"));
// Make key value string array to list of keyvalues and add brackets again
let resultString = `{${resultKeyValuePairStrings.join(",")}}`;
// Log the parsed JSON Id
let obj = JSON.parse(resultString);
console.log(obj);
console.log(obj.Id);
答案 1 :(得分:0)
通过转换为JSON,您可以使用split
轻松获得所需的项目:
var result = sCountry.split(/ *, */);
var path = result[1].split(/ *: */)[1];
var id = result[2].split(/ *: */)[1];
请添加一些错误检查,以防万一您收到了意外格式的字符串。