修复在元素名称周围没有引号的JSON

时间:2015-11-21 23:54:17

标签: javascript jquery json

我有这个破JSON字符串

    {
    sources: [{
        file: "/images/image1.png",
        label: "Cat"
    }, {
        file: "/images/image2.png",
        label: "Cat2"
    }, {
        file: "/images/image3.png",
        label: "Cat3"
    }],
    skin: "",
    size: "1330",
    width: 728,
    height: 410,
    preload: "auto",
    startparam: "start",
    other: [],
    config: {
        color: '#FFFFFF',
        fontSize: 15,
        fontFamily: "Verdana",
        backgroundOpacity: 0
    },
    "sharing": {
        code: "265235EF",
        link: "LINK HERE"
    }
}

但是你可以看到元素名称周围没有引号,这意味着当我尝试从中获取信息时,它就无法工作。

有没有办法让我把它修改成这个(添加引号)

{
   "sources": [
      {
         "file": "/images/image1.png",
         "label": "Cat"
      },
      {
         "file": "/images/image2.png",
         "label": "Cat2"
      },
      {
         "file": "/images/image3.png",
         "label": "Cat3"
      }
   ],
   "skin": "",
   "size": "1330",
   "width": 728,
   "height": 410,
   "preload": "auto",
   "startparam": "start",
   "other": [],
   "config": {
      "color": "#FFFFFF",
      "fontSize": 15,
      "fontFamily": "Verdana",
      "backgroundOpacity": 0
   },
   "sharing": {
      "code": "265235EF",
      "link": "LINK HERE"
   }
}

2 个答案:

答案 0 :(得分:2)

使用JSON.stringify()例如:

var obj = {
    sources: [{
        file: "/images/image1.png",
        label: "Cat"
    }, {
        file: "/images/image2.png",
        label: "Cat2"
    }, {
        file: "/images/image3.png",
        label: "Cat3"
    }],
    skin: "",
    size: "1330",
    width: 728,
    height: 410,
    preload: "auto",
    startparam: "start",
    other: [],
    config: {
        color: '#FFFFFF',
        fontSize: 15,
        fontFamily: "Verdana",
        backgroundOpacity: 0
    },
        "sharing": {
        code: "265235EF",
        link: "LINK HERE"
    }
}

var json = JSON.stringify( obj );
console.log( json )

答案 1 :(得分:1)

像这样使用JSON.stringify()



var j =    {
    sources: [{
        file: "/images/image1.png",
        label: "Cat"
    }, {
        file: "/images/image2.png",
        label: "Cat2"
    }, {
        file: "/images/image3.png",
        label: "Cat3"
    }],
    skin: "",
    size: "1330",
    width: 728,
    height: 410,
    preload: "auto",
    startparam: "start",
    other: [],
    config: {
        color: '#FFFFFF',
        fontSize: 15,
        fontFamily: "Verdana",
        backgroundOpacity: 0
    },
    "sharing": {
        code: "265235EF",
        link: "LINK HERE"
    }
};

document.write(JSON.stringify(j));