2012-07-24 53 views
1

我想知道我可以使用jquery拆分此...拆分的String []做出不同的JSON

"{"answer":["q1001-a2","q1002-a2","q1003-a2","q1004-a2","q1005-a2","q1006-a2"]}" 

這樣我就可以進行以下JSON ...

{ 
    "d": [ 
     { 
      "question": 1001, 
      "answer": "a2" 
     }, 
     { 
      "question": 1002, 
      "answer": "a2" 
     } 
     ] 
} 

謝謝。

+0

您建議使用[分割](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)函數。你有什麼嘗試? – 2012-07-24 09:53:22

回答

1

循環answer,將元素拆分-,創建新元素,然後將其推送到d

var ret = {d: []}; 
// if you have json string, then you could jQuery.parseJSON to parse it 
var obj = {"answer":["q1001-a2","q1002-a2","q1003-a2","q1004-a2","q1005-a2","q1006-a2"]}; 
var answers = obj.answer, tmp, i; 
for (i = 0; i < answers.length; i++) { 
    tmp = answers[i].split('-'); 
    ret.d.push({"question": tmp[0], "answer": tmp[1]}); 
} 

The live DEMO

+0

抱歉只好對JSON做一些細微的改動,我會如何使用你的解決方案來分割 - 「」{「answer」:[「q1001-Blend」,「q1002-Lowlands」,「q1003-Two」,「q1004-Ireland 「,」q1005-Bushmills「,」q1006-Suntory「]}'' – thatuxguy 2012-07-24 10:00:32

+0

@thatuxguy這有什麼區別嗎? – xdazz 2012-07-24 10:29:34

+0

我一直在獲取Uncaught TypeError:無法讀取未定義的屬性「長度」 – thatuxguy 2012-07-24 10:44:37

0

http://api.jquery.com/jQuery.parseJSON/

猜測這應該有所幫助。

"{"answer":["q1001-a2","q1002-a2","q1003-a2","q1004-a2","q1005-a2","q1006-a2"]}" 

應該像

'{"answer":["q1001-a2","q1002-a2","q1003-a2","q1004-a2","q1005-a2","q1006-a2"]}' 

你可以嘗試更換「Q1001」和「 - 」與字符串的正則表達式將匹配JSON非標準,但它不是一個通用的解決方案

0

使用jQuery中格式化函數象下面這樣:

var string = "{\"key\":\"val}{ue\"}{'key':'val}{ue'}{ \"asdf\" : 500 }"; 
var result = string.match(/('.*?')|(".*?")|(\d+)|({)|(:)|(})/g); 
var newstring = ""; 
for (var i in result) { 
    var next = parseInt(i) + 1; 
    if (next <= result.length) { 
     if (result[i] == "}" && result[next] == "{") { 
     newstring += "},"; 
     } 
     else { 
     newstring += result[i]; 
    } 
} 

這個代碼詳細解釋了jQuery - $.each loop through json code

相關問題