将Javascript字符串转换为名称/值对对象

时间:2018-11-29 21:09:00

标签: javascript reactjs

如何将以下字符串转换为名称/值对

id:"Ebene_1",version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",xmlSpace:"preserve" d:"M8.5,23h-3C5.2,23,5,23.2,5,23.5S5.2,24,5.5,24h3C8.8,24,9,23.8,9,23.5S8.8,23,8.5,23z" height:"1",width:"3",x:"12",y:"28"

这样我就可以将结果作为参数传递给

createElem(type, attribs){
        this.svgElem = React.createElement(type,attribs)
        console.log(this.svgElem)

我曾考虑过将其拆分为逗号上的数组,但不适用于d:属性

感谢收到任何指针

3 个答案:

答案 0 :(得分:1)

使用此JavaScript方法JSON.parse(string);

Docs

答案 1 :(得分:0)

首先必须确保您的字符串格式正确。然后使用JSON.parse()

var string = '{"name": "bob", "age": "26"}';
var k = JSON.parse(string);
console.log(k);

答案 2 :(得分:0)

尝试使用正则表达式:

var m, 
    result = {},
    re = /([a-z]+):("[^"]+")/gi,
    str = 'id:"Ebene_1",version:"1.1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",xmlSpace:"preserve" d:"M8.5,23h-3C5.2,23,5,23.2,5,23.5S5.2,24,5.5,24h3C8.8,24,9,23.8,9,23.5S8.8,23,8.5,23z" height:"1",width:"3",x:"12",y:"28"';

do {
    m = re.exec(str);
    if (m) result[m[1]] = m[2];
} while (m);
console.log(result);

输出:

d: ""M8.5,23h-3C5.2,23,5,23.2,5,23.5S5.2,24,5.5,24h3C8.8,24,9,23.8,9,23.5S8.8,23,8.5,23z""
height: ""1""
id: ""Ebene_1""
xmlSpace: ""preserve""
version: ""1.1""
width: ""3""
x: ""12""
xmlns: ""http://www.w3.org/2000/svg""
y: ""28""