2012-11-24 130 views
0

我是从数据的基础上读取数据: 我有值I要阵列转换成JSON阵列 - JSON.stringify

for (var index in entities) {                 
    console.log(entities[index].PartitionKey);                  
    console.log(entities[index].RowKey);                  
    console.log(entities[index].Details);                
    console.log(entities[index].Date); 
    } 

上面将打印所有我想要的数据。 现在我想将其转换为Json对象。我怎样才能做到这一点 。

我已经使用并意识到我可以使用JSON.stringify,但是当我在此上下文中尝试此操作时,它会给出错误。

我试图保持在for循环:

jasonarray[index1].PartitionKey  = entities[index].PartitionKey; 
jasonarray[index1].RowKey   = entities[index].RowKey; 

JSON.stringify({ key: jasonarray[index1].PartitionKey, RowKey: jasonarray[index1].RowKey) 

但是,当涉及到执行此功能它给为未定义。

所有我找的变种X:

where x is a 

[ 

{partionkey: "val",key: "val"} 
{partionkey: "val",key1: "val"} 
{partionkey: "val",key2: "val"} 

] 
+1

是什么'entities'看起来像它的原始状态?如果它是一个数组,你不应该使用'for in',其目的是迭代对象属性。 –

+0

谢谢迈克尔。它是由我的数据库查询返回的数组。你可以让我知道如何做到这一点 –

+1

做'console.log(JSON.stringify(实体))',所以我们可以看到原始'实体'数组的结构。 –

回答

2

的Javascript: 工作样本http://fiddle.jshell.net/xrB8J/

var entities = [ 
    {PartitionKey: 'a', RowKey: 5, Details:'details 1', Date:'01.01.2012' }, 
    {PartitionKey: 'b', RowKey: 7, Details:'details 2', Date:'02.01.2012' }, 
    {PartitionKey: 'c', RowKey: 3, Details:'details 3', Date:'03.01.2012' } 
]; 

var a = new Array(); 
for(i = 0; i < 3; i++) 
    a.push({ 
     PartitionKey: entities[i].PartitionKey, 
     RowKey: entities[i].RowKey 
    }); 

alert(JSON.stringify(a)); 

或C#:

string json = (new JavascriptSerializer()).Serialize(entities.Select(x => new 
    { 
     x.PartitionKey, 
     x.RowKey 
    } 
));