使用JSON.stringifyf如何添加方括号?

时间:2015-05-11 20:51:10

标签: jquery json

我有生成JSON字符串的代码

{"did":50,"pid":"66","cid":"2","qty":1,"skus":{"ssid":"B931627", "type":"fab"
,"qty":1,"style":""}}

但我需要将其格式化为

{"did":50,"pid":"66","cid":"2","qty":1,"skus":[{"ssid":"B931627", "type":"fab"
,"qty":1,"style":""}]}

这是我到目前为止所做的:

 var dataAttributes = {
   did : $(selector).data('did'),
   pid : $(selector).data('pid'),
   cid : $(selector).data('cid'),
   qty : '1',
   coveroptionskus : var ssus = {
         ssid : $(selector).data('ssid'),
         type : '',
         qty : 1,
         style : ''
       }
  };

1 个答案:

答案 0 :(得分:1)

""属性名称附近添加dataAttributes双引号,值

 var dataAttributes = {
   "did" : $(selector).data("did"),
   "pid" : $(selector).data("pid"),
   "cid" : $(selector).data("cid"),
   "qty" : "1",
   // removed `var`
   // set as `skus` property as `Array`,
   // set properties of object
   // within `skus` array
   "skus" : [{
             "ssid" : $(selector).data("ssid"),
             "type" : "",
             "qty" : 1,
             "style" : ""
            }]
  };
  // call `JSON.stringify()` with `dataAttributes` as parameter 
  JSON.stringify(dataAttributes);