2014-02-27 77 views
0

I搜索但我無法找到任何解決方案。我得到這個字符串從服務器:將JSON字符串轉換爲JavaScript對象進行迭代

[ 
    { 
    'id': 0, 
    'name': 'Adventure Works', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Adventure Works]' 
    }, 
    { 
    'id': 1, 
    'name': 'Channel Sales', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Channel Sales]' 
    }, 
    { 
    'id': 2, 
    'name': 'Direct Sales', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Direct Sales]' 
    }, 
    { 
    'id': 3, 
    'name': 'Finance', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Finance]' 
    }, 
    { 
    'id': 4, 
    'name': 'Mined Customers', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Mined Customers]' 
    }, 
    { 
    'id': 5, 
    'name': 'Sales Summary', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Sales Summary]' 
    }, 
    { 
    'id': 6, 
    'name': 'Sales Targets', 
    'uniqueName': '[AdventureWorksDW2012Multidimensional-EE].[Sales Targets]' 
    } 
] 

但它是一個字符串,我想它作爲一個JavaScript對象。如果我從字符串中手動刪除第一個和最後一個",那麼每個事情都可以,但是如何將此字符串轉換爲JavaScript Object?

更新

如果使用jQuery解析如下:

var data = $.parseJSON(response.d); 

我得到這個錯誤:

Uncaught TypeError: Cannot use 'in' operator to search for '727' in {'id':0,'name':'Adventure Works','uniqueName':'[AdventureWorksDW2012Multidimensional-EE].[Adventure Works]'},{'id':1,'name':'Channel Sales','uniqueName':'[AdventureWorksDW2012Multi...<omitted>...'} 

**編輯**

這是JSFIDDLE鏈接。

+1

['JSON.parse(yourString);'](https://developer.mozilla.org/EN-US /文檔/網絡/的JavaScript /參考/ Global_Objects/JSON /分析)? –

+0

更新後,您沒有顯示相關的代碼。給定的codesample中沒有'in'運算符。 – Sirko

回答

1

使用JSON.parse("[{...}]");將其轉換爲Javascript對象。

+0

我在jsbin中嘗試你的方式[這裏](http://jsbin.com/disegixa/1/edit?js,console),但我得到一個錯誤。 'Unexcepted token'' – MBehtemam

+0

是的。這是一個[小提琴](http://jsfiddle.net/MBehtemam/89pRk/),我不能解析和迭代it.thanks – MBehtemam

+1

我意識到這個問題。您的JSON字符串無效。你應該在json中使用雙引號,而不是單個。看到這個:http://jsfiddle.net/89pRk/1/ – sedran

1

您可以使用JSON.parse()方法爲您的JSON字符串轉換爲Javascript對象。

0

可以使用:

JSON.parse("some json stringified object") 

要從JSON對象使用創建字符串:

JSON.stringify(OBJECT); 
相關問題