Jquery - 如何将Object数组转换为Json字符串

时间:2017-09-19 09:27:18

标签: jquery json

SymbologyObjectValuesArray

var SymbologyObject = {};
var ValuesArray = [];

将一些东西放入其中,如下所示:

var ValueOfField = "tree";
ValuesArray[ValueOfField] = [];

var localStyle = {};
localStyle.fill = "#ffff";
localStyle.stroke = "#cccc";
localStyle.width = 3;
localStyle.value = ValueOfField;

ValuesArray[ValueOfField] = localStyle;

SymbologyObject.type = "Unique";
SymbologyObject.label = "test";

SymbologyObject.attr = "attribute";

SymbologyObject.values = ValuesArray;

当我使用console.log(SymbologyObject);输出时:

attr:"attribute"
label:"test"
type:"Unique"
values:
tree:{fill: "#ffff", stroke: "#cccc", width: "3", value: "tree"}

我将它转换为json:

JSON.stringify(SymbologyObject);

上述代码的输出:

{"type":"Unique","label":"test","attr":"attribute","values":[]}

但我想要低于输出:

{"type":"Unique","label":"test","attr":"attribute","values":[tree:{"fill": "#ffff", "stroke": "#cccc", "width": "3", "value": "tree"}]}

有什么问题?

2 个答案:

答案 0 :(得分:0)

首先,你的变量初始化是错误的 你必须像下面这样初始化。

var SymbologyObject = {};
var ValuesArray = {}; //<< CHANGE

其次,请参阅下面的更改。

var ValueOfField = "tree";
ValuesArray[ValueOfField] = {}; //<<CHANGE

var localStyle = {};
localStyle.fill = "#ffff";
localStyle.stroke = "#cccc";
localStyle.width = 3;
localStyle.value = ValueOfField;

ValuesArray[ValueOfField] = localStyle;

SymbologyObject.type = "Unique";
SymbologyObject.label = "test";

SymbologyObject.attr = "attribute";

SymbologyObject.values = ValuesArray;

所以,输出将如下所示。

{"type":"Unique","label":"test","attr":"attribute","values":{"tree1":{"fill":"#ffff","stroke":"#cccc","width":3,"value":"tree1"},"tree":{"fill":"#ffff","stroke":"#cccc","width":3,"value":"tree"}}}

答案 1 :(得分:0)

首先检查您的JSON,因为它不是有效的JSOn。 `

{
    "type": "Unique",
    "label": "test",
    "attr": "attribute",
    "values": [tree: {
        "fill": "#ffff",
        "stroke": "#cccc",
        "width": "3",
        "value": "tree"
    }]
}

`