【问题标题】:Array conversion into a json array - JSON.stringify数组转换成 json 数组 - JSON.stringify
【发布时间】:2012-11-24 20:38:42
【问题描述】:

我正在从数据库中读取数据: 我有我想要的价值观

    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,但是当我在这种情况下在这里尝试时,它会给出错误。

我尝试保持在 forloop 中:

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

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

但是在执行这个函数时它是未定义的。

我正在寻找的只是 var x:

where x is a 

[

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

]

【问题讨论】:

  • entities 的原始状态是什么样的?如果它是一个数组,则不应使用for in,其目的是迭代对象属性。
  • 谢谢迈克尔。它是我的数据库查询返回的数组。你能告诉我怎么做吗
  • console.log(JSON.stringify(entities)) 这样我们就可以看到原始entities 数组的结构了。

标签: javascript json node.js


【解决方案1】:

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
    }
));

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2017-10-22
    • 1970-01-01
    • 2015-08-04
    • 2016-08-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多