[英]How to validly parse a non JSON conform stringified data format into an object?
I wanna know if i can convert我想知道我是否可以转换
let serverProps = "{
server-name: New Server,
server-id: 165894343,
server-description: New Server Description,
server-avatar: ./server_avatars/165894343AEAVATAR.jpg,
server-banner: 0
};"
To an object please help求一个object帮忙
The best solution is to fix whatever is outputting your code into a proper JSON format.最好的解决方案是将您的代码输出为正确的 JSON 格式。
But for this you can split on new lines.但是为此,您可以在新行上拆分。 Loop over that and split on colon and build your object.
循环并在冒号上拆分并构建您的 object。
const serverProps = `{ server-name: New Server, server-id: 165894343, server-description: New Server Description, server-avatar:./server_avatars/165894343AEAVATAR.jpg, server-banner: 0 };` const out = serverProps.split(/,?\n/).reduce((o, line) => { const [key, value] = line.split(/\s?:\s?/); if (value) { o[key] = value } return o; }, {}); console.log(out);
In case of a multiline format like the one given by the OP one could come up with a two folded regex based approach.如果是像 OP 给出的那样的多行格式,可以提出一种基于二折正则表达式的方法。
replace
one first gets rid of the leading and trailing curly braces , including newlines and the terminating semicolonreplace
one first去掉前导和尾随花括号,包括换行符和终止分号matchAll
a regex which uses named capturing groups and does create the final result by reduce
ing the array of all the captured groups.matchAll
是一个使用命名捕获组的正则表达式,并通过reduce
所有捕获组的数组来创建最终结果。 const serverProps = `{ server-name: New Server, server-id: 165894343, server-description: New Server Description, server-avatar:./server_avatars/165894343AEAVATAR.jpg, server-banner: 0 };`; console.log( serverProps ); console.log( serverProps.replace((/^{\n|\n}.*$/gm), '') ); console.log( Array.from( serverProps // see... [https://regex101.com/r/tgYr1x/4].replace((/^{\n|\n}.*$/gm), '') // see... [https://regex101.com/r/tgYr1x/1].matchAll(/^\s*(?<key>[^:]+?)\s*:\s*(?<value>.*?),*$/gm) ).reduce((merger, { groups: { key, value } }) => Object.assign(merger, { [ key ]: value }), {} ) );
Your JSON format seems incorrect: but for reference您的 JSON 格式似乎不正确:但供参考
You can simply use你可以简单地使用
JSON.parse(your_string);
example:例子:
JSON.parse('{ "name" : "testuser" }')
results:结果:
{ name: 'testuser' }
For reverse JSON.stringify() is used对于反向 JSON.stringify() 使用
link for reference:参考链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.