Javascript 在JS中将流提取为JSON
帮助了解如何在javascript中将以下字符串转换为JSON。我需要日期(20181218-20181228)及其相应的价格(formattedPrice=$469)。谢谢 尝试在文本中添加引号和:但在解析时遇到错误,因为键(20181218-20181228)不特定您可以像这样使用Javascript 在JS中将流提取为JSON,javascript,jquery,Javascript,Jquery,帮助了解如何在javascript中将以下字符串转换为JSON。我需要日期(20181218-20181228)及其相应的价格(formattedPrice=$469)。谢谢 尝试在文本中添加引号和:但在解析时遇到错误,因为键(20181218-20181228)不特定您可以像这样使用.split()和.reduce() function parseWeirdString(str) { return str.split(/},?/g).reduce((obj, row) => {
.split()
和.reduce()
function parseWeirdString(str) {
return str.split(/},?/g).reduce((obj, row) => {
const rowParts = row.split(/\={/);
if (rowParts.length > 1) {
obj[rowParts[0].trim()] = rowParts[1].split(/,/g).reduce((innerObj, keyValue) => {
const keyValueParts = keyValue.split(/=/);
innerObj[keyValueParts[0].trim()] = keyValueParts[1].trim();
return innerObj;
}, {});
}
return obj;
}, {});
}
应返回如下所示的对象:
{
"20181218-20181228": {
"currencyCode": "USD",
"totalPrice": "469.4",
"formattedPrice": "$469",
"cheapest": "false"
},
"20181218-20181226": {
"currencyCode": "USD",
"totalPrice": "469.4",
"formattedPrice": "$469",
"cheapest": "false"
},
"20181218-20181227": {
"currencyCode": "USD",
"totalPrice": "451.4",
"formattedPrice": "$451",
"cheapest": "false"
}
}
请注意,所有值都是字符串,包括
“true”
和“false”
。如果值中有逗号等,则此操作将失败。Replace all=with:using Replace all,Remove',最后将{and}放在start和end中。所有非数字和非布尔值都应放在“”中。你可以为此编写正则表达式。如果你在这方面需要帮助,请告诉我
objstr = `{"20181218-20181228":{"currencyCode":"USD", "totalPrice":469.4, "formattedPrice":"$469", "cheapest":false},
"20181218-20181226":{"currencyCode":"USD", "totalPrice":469.4, "formattedPrice":"$469", "cheapest":false}}`;
//replace, remove last , ,,, Put {} in start and end ,,,,
obj = JSON.parse(objstr);
console.log(obj);
您可以使用下面的正则表达式来解析此对象。我已经为您的需要创建了一个自定义正则表达式,您可以自定义它。还有一些其他选项,如eval,但并不安全。顺便说一句,因为你是新来的,所以通知你可以投票(比如)帮助你的答案:)
你从哪里得到这么奇怪的线?您可以修改源吗?不,它是不可修改的。它是基于来自外部API的响应,那么您尝试过什么?这里的目标是帮助其他人修复他们的代码,而不是成为一个免费的代码编写服务尝试替换equals to:并在equals前后的文本周围添加引号,以便转换为JSON格式。因此,请将您迄今为止在问题中尝试过的内容以及产生的错误包括在内。有一种更快的添加“”的方法吗?。传入字符串中也没有引号。您可以向上投票(喜欢)答案以帮助您:)
objstr = `{"20181218-20181228":{"currencyCode":"USD", "totalPrice":469.4, "formattedPrice":"$469", "cheapest":false},
"20181218-20181226":{"currencyCode":"USD", "totalPrice":469.4, "formattedPrice":"$469", "cheapest":false}}`;
//replace, remove last , ,,, Put {} in start and end ,,,,
obj = JSON.parse(objstr);
console.log(obj);
objstr22 = `{20181218-20181228={currencyCode=USD, totalPrice=469.4, formattedPrice=$469, cheapest=false},
20181218-20181226={currencyCode=USD, totalPrice=469.4, formattedPrice=$469, cheapest=false},
20181218-20181227={currencyCode=USD, totalPrice=451.4, formattedPrice=$451, cheapest=false}}`;
objstr22 = objstr22
.replace(/ /g, "")
.replace(/([\-\w\d]+)=/g, '"$1"=')
.replace(/=([\w\d\.\$]+)/g, ':"$1"')
.replace(/=([[{])/g, ":$1");
console.log(objstr22);
let obj22 = JSON.parse(objstr22);
for (o of Object.keys(obj22)) {
console.log(o, obj22[o]);
}