[英]best way to convert from string to javascript object
I have this string:我有这个字符串:
periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half
What is the best way to convert it to this object?将其转换为该对象的最佳方法是什么?
periodRows: {
soccer: {
on: 1,
periods: 1,
prematchPeriods: 1,
label: '1st Half',
}
}
Note that I do not control the string, therefore I can not change it.请注意,我不控制字符串,因此我无法更改它。
Thank you谢谢
const rec = (tokens, index, target) => {
const prop = tokens[index];
if (tokens.length - 1 === index) {
const [lastProp, value] = prop.split(/[:=]/);
target[lastProp] = value;
return target[lastProp];
}
if (prop && !target[prop]) {
target[prop] = {};
}
return target[prop];
}
"periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half".split(',').reduce((acc, val) => {
const tokens = val.split('.');
let target = acc;
for (let i = 0; i < tokens.length; i++) {
target = rec(tokens, i, target);
}
return acc;
}, {});
By default JS cannot recognize numbers inside of strings.默认情况下,JS 无法识别字符串中的数字。 You have to cast it explicitly.
你必须明确地投射它。 You can update code of
rec
function with this piece.你可以用这块更新
rec
函数的代码。
if (tokens.length - 1 === index) {
const [lastProp, stringValue] = prop.split(/[:=]/);
const parsedValue = +stringValue;
const value = Number.isNaN(parsedValue) ? stringValue: parsedValue;
target[lastProp] = value;
return target[lastProp];
}
Functionally, a bit shorter.在功能上,有点短。
const f = (obj, keyPath, value) => {
if (keyPath.length === 0) {
return Number.isNaN(Number(value)) ? value : Number(value);
}
const key = keyPath[0];
if (!obj[key]) {
obj[key] = {};
}
obj[key] = f(obj[key], keyPath.slice(1), value);
return obj;
};
const str = "periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half";
str.split(",")
.map(token => token.split(/[:=]/))
.map(record => ({keyPath: record[0].split("."), value: record[1]}))
.reduce((obj, item) => f(obj, item.keyPath, item.value), {});
The string format you have above is in bad format, the only way to convert it is by first converting it into a string in json-like format, something like the following (notice a json-like string should always be enclosed by {}):您上面的字符串格式格式错误,转换它的唯一方法是首先将其转换为类似 json 格式的字符串,如下所示(注意类似 json 的字符串应始终用 {} 括起来) :
var periodRows = '{"soccer":{"on":1,"periods":1,"prematchPeriods":1,"label":"1st Half"}}';
Then you'd be able to perform the conversion:然后你就可以执行转换:
//String to Json
const str = JSON.parse(periodRows);
console.log (str);
//Json to string
var periodRows = {
soccer: {
on: 1,
periods: 1,
prematchPeriods: 1,
label: '1st Half',
}
}
var myStr = JSON.stringify(periodRows);
console.log (myStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.