我有一个具有data-options属性名称的元素,每个元素都有不同的配置,它不是为便于阅读和易于维护而格式化的json。
<table scoa-table data-options="
responsive:true,
setHeaders:['header1','header2','header3'],
colWidth : 300,
data : {
"data1" : "value1",
"data2" : "value2",
"data3" : "value4",
}`
"></table>
我需要将字符串解析为逗号分隔的值
到目前为止,我有以下内容:
var foo = jQuery("[scoa-table]").attr("data-options"),
result = foo.split(/,(?![^\[]*\])/gm)
但只能在括号中使用,而不能在括号中使用
这是我的期望
(3) ["responsive:true",
"setHeaders:['header1','header2','header3']",
"colWidth : 300",
'data : {"data1" : "value1","data2" : "value2","data3" : "value4",}'
]
答案 0 :(得分:0)
而不是使用逗号,请尝试将“ \ n”换行作为拆分参数: 对于您的输入,您可以使用:
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
boxSelectionEnabled: false,
autounselectify: true,
style: [{
selector: "node",
css: {
label: "data(name)", //access the nodes data with "data(...)"
// label: "data(id)",
"text-valign": "center",
"text-halign": "center",
height: "60px",
width: "100px",
shape: "rectangle",
"background-color": "data(faveColor)"
}
},
{
selector: "edge",
css: {
"curve-style": "bezier",
"control-point-step-size": 40,
"target-arrow-shape": "triangle"
}
}
],
elements: {
nodes: [{
data: {
id: "Top",
faveColor: "#2763c4",
name: "Steve"
}
},
{
data: {
id: "yes",
faveColor: "#37a32d",
name: "Larry"
}
},
{
data: {
id: "no",
faveColor: "#2763c4",
name: "Kiwi"
}
},
{
data: {
id: "Third",
faveColor: "#2763c4",
name: "Alex"
}
},
{
data: {
id: "Fourth",
faveColor: "#56a9f7",
name: "Vader"
}
}
],
edges: [{
data: {
source: "Top",
target: "yes"
}
},
{
data: {
source: "Top",
target: "no"
}
},
{
data: {
source: "no",
target: "Third"
}
},
{
data: {
source: "Third",
target: "Fourth"
}
},
{
data: {
source: "Fourth",
target: "Third"
}
}
]
},
layout: {
name: "dagre"
}
}));
顺便说一句:您可能也需要替换body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
left: 0;
top: 0;
float: left;
position: absolute;
}
,并在分隔行中使用最后一个逗号,例如:
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<script src="https://unpkg.com/cytoscape@3.3.0/dist/cytoscape.min.js">
</script>
<!-- cyposcape dagre -->
<script src="https://unpkg.com/dagre@0.7.4/dist/dagre.js"></script>
<script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-dagre/1.5.0/cytoscape-dagre.js"></script>
</head>
<body>
<div id="cy"></div>
</body>
</html>
答案 1 :(得分:0)
将对象放在对象上并使用JSON.stringify
将键和值转换为字符串,然后再将其压入数组
var foo = {
responsive: true,
setHeaders: ['header1', 'header2', 'header3'],
colWidth: 300,
data: {
"data1": "value1",
"data2": "value2",
"data3": "value4",
}
}
let arr = [];
for (let keys in foo) {
arr.push(`${keys}:${JSON.stringify(foo[keys])}`)
}
console.log(arr)