2014-05-05 228 views
-1

我想從另一個js文件中獲取json對象。我發現最終結果是字符串形式的json看起來像這樣如何將字符串json轉換爲JSON對象

"[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }];" 

我該如何轉換成JSON對象?這裏是我的代碼

var jsonData = $.get("/Scripts/dummy.js", function (data) { 

      console.log(data); 
      return data; 
     }); 

回答

0

使用JSON.stringify()。

var json = JSON.stringify(data);

0

要轉換的字符串JSON對象,使用JSON.parse:

變種的JSONObject = JSON.parse(jsonText);

var jsonData = $.get("/Scripts/dummy.js", function (data) { 

     console.log(data); 
     return JSON.parse(data); 
    }); 
0

你需要的是JSON.parse()來:

var json = '[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }]'; 
JSON.parse(json); 
0

首先,您需要從對象的字符串刪除尾隨;並使用適當的單/雙引號包裝:

// Your string used all double quotes, replace the outermost quotes with single 
// quotes as shown below. Also notice that the ; has been moved outside the 
// string, semicolons are not permitted as part of JSON object strings 
var x = '[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }]';  

,然後用JSON.parse()返回一個有效的JSON對象:

JSON.parse(x); 
=> [ { part: 'Part1', dwg: 'ASAD' }, 
    { part: 'Part2', dwg: 'B' } ] 
相關問題