我有一个字符串,其中对象名称与字段名称之间用点号分隔,如下所示:
{\"person.firstName\":\"Ahmed\",\"person.job\":\"Doctor\",\"products.packName\":\"antibiotic\",\"products.packSize\":\"large\"}}";
我想将其解析为json格式:
"{\"person\": {\"firstName\":\"Ahmed\",\"job\":\"Doctor\",},\"products\": {\"packName\":\"antibiotic\",\"packSize\":\"large\"}}";
有没有一种有效的算法?
答案 0 :(得分:0)
假设左侧可能有多个点
let parsedObj = JSON.parse(<..YOUR STRINGIFIED JSON..>);
let myObj = {};
Object.keys(parsedObj).forEach((key) => {
let val = parsedObj[key];
let subKeys = key.split(".");
let currentRef = myObj;
subKeys.forEach((subKey, idx) => {
if(idx === subKeys.length - 1) {
currentRef[subKey] = val;
} else {
currentRef[subKey] = currentRef[subKey] || {};
currentRef = currentRef[subKey];
}
});
});
let finalString = JSON.stringify(myObj);
P.S。您的字符串结尾似乎包含一个额外的}
答案 1 :(得分:0)
也许这对您有帮助。
var str='{\"person.firstName\":\"Ahmed\",\"person.job\":\"Doctor\",\"products.packName\":\"antibiotic\",\"products.packSize\":\"large\"}';
var newObj={}
var json=JSON.parse(str);
for (i in json) {
var splt=i.split('.');
var key=splt[0];
var subkey=splt[1];
if(!(key in newObj)) {
newObj[key]={};
}
newObj[key][subkey]=json[i];
}
//if you need string use str or not use newObj
var str=JSON.stringify(newObj);
console.log(str);
console.log(newObj);
console.log(newObj.person);
console.log(newObj.person.firstName);
console.log(newObj.person.job);