2010-12-07 61 views
3

首先我通过web服务器得到JSON数据就像我希望得到JSON数据阵列的一个特定的条目,并做了一些修改

$.getJSON(url,function(){ 
//my callback function; 
}); 

现在我已经得到的数据如下:

{entries:[{title:'foo',id:'UUID',finished:null},{title:'bar',id:'UUID',finished:null},{title:'baz',id:'UUID',finished:null}]} 

我必须找到一个特定的JSON条目由它的UUID,之后,我需要修改例如其中的一部分,使一个新的JSON数据:

{title:'foo',id:'UUID',finished:true} 

,通过使用

$.post(url, data); 

我完全同意这个情况迷失了自己发送回服务器...谁能帮助?

回答

6

假设你已经把数据在一个名为result变量,就像这样:

var result = {entries:[{title:'foo',id:'UUID',finished:null},{title:'bar',id:'UUID',finished:null},{title:'baz',id:'UUID',finished:null}]} 

你可以做一个for循环:

for (var i=0; i<result.entries.length; i++) { 
    if (result.entries[i].id == 'the_UUID_you_are_looking_for') { 
    var entry = result.entries[i]; // "entry" is now the entry you were looking for 
    // ... do something useful with "entry" here... 
    } 
} 

编辑 - 我已经写了下面的完整解决方案,以进一步说明主意并避免误解:

// Get data from the server 
$.getJSON("url", function(result) { 

    // Loop through the data returned by the server to find the UUId of interest 
    for (var i=0; i<result.entries.length; i++) { 
    if (result.entries[i].id == 'the_UUID_you_are_looking_for') { 
     var entry = result.entries[i]; 


     // Modifiy the entry as you wish here. 
     // The question only mentioned setting "finished" to true, so that's 
     // what I'm doing, but you can change it in any way you want to. 
     entry.finished = true; 


     // Post the modified data back to the server and break the loop 
     $.post("url", result); 
     break; 
    } 
    } 
} 
+0

谢谢@Jakob,但我的JSON数据是由$ .getJOSN();函数,我没有这种格式的确切文件...我不知道如何使得像var result = {entries:[...]} – 2010-12-07 15:54:48

1

试试这个:

var modified = false, myUuid = 'some uuid'; 

for (i = 0; i < data.entries.length; i++) { 
    if (data.entries[i].id === myUuid) { 
     data.entries[i].finished = true; 
     modified = true; 
     break; 
    } 
} 

if (modified) { 
    $.post(url, data); 
} 
0

您需要遍历数据。或者你可以重构你的JSON:

{"entries":{"UUID1":{"title":"foo", "finished": false }}, {"UUID2":{"title":"bar", "finished":false}}} 
相关问题