2015-11-21 25 views
0

我有這個破碎的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" 
    } 
} 

但正如你所看到的元素名稱不要有他們周圍的報價,這意味着修正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" 
    } 
} 
+0

你想要做什麼?定期解決這個問題在什麼樣的環境下?不恰當的字符串來自哪裏? – JohnB

+0

你的第一個代碼是有效的JavaScript。你不能把它放到一個變量中,並執行'JSON.stringify(變量)'? – Sergio

回答

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

使用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));