简体   繁体   English

node.js + API + Json格式

[英]node.js + API + Json formatting

I am developing an Rest API using node.js + postgis.In that my problem is in formatting the result 我正在使用node.js + postgis开发Rest API,因为我的问题是格式化结果

Consider my DB look like below: 考虑我的数据库如下所示:

name        key         value
xxxxxx      population  232
xxxxxx      marginal    24
yyyyyy      population  6372
yyyyyy      marginal    566

I want the output as below: 我想要的输出如下:

[{
name:xxxx
key:population
value:232
key:marginal
value:24
},
{
name:yyyyy
key:population
value:6372
key:marginal
value:566
}]

I am executing the following query: 我正在执行以下查询:

SELECT  name, key, value
FROM    map70
WHERE   key in ('population', 'marginal')
GROUP BY
        name, key, value

But i am getting output as below: 但是我得到的输出如下:

[{
name:xxxx
key:population
value:232
},
{
name:xxxx
key:marginal
value:24
},
{
name:yyyyy
key:population
value:6372
},
{
name:yyyy
key:marginal
value:566
}
]

How can i have the output which i want..Help me solve this.Thanks in advance. 我怎样才能得到想要的输出。.帮助我解决这个问题。谢谢。

You can't have the output you want. 您无法获得所需的输出。

[{
name:xxxx
key:population
value:232
key:marginal
value:24
},
{
name:yyyyy
key:population
value:6372
key:marginal
value:566
}]

In javascript and usually all hashtables, you cannot have multiple keys with the same name. 在JavaScript和通常所有的哈希表中,不能有多个具有相同名称的键。

What you want is something like this: 您想要的是这样的:

[{
"name":"xxxx",
"population": 232,
"marginal": 24
},
{
"name":"yyyyy",
"population": 6372,
"marginal": 566
}]

Or something like this: 或类似这样的东西:

[{
"name":"xxxx",
"keys": [
 ["population", 232],
 ["marginal", 24]
]
},
{
"name":"yyyyy",
"keys": [
  ["population", 6372],
  ["marginal", 566]
]
}]

To get the second output, iterate over all your results. 要获得第二个输出,请遍历所有结果。 You need some kind of collection in which you can save the objects you need for output. 您需要某种收集,您可以在其中保存输出所需的对象。 For each line, check if there is already an object created. 对于每一行,检查是否已经创建了一个对象。 If not create one, if there is one add to the "keys" array. 如果不创建,则在“键”数组中添加一个。

obj.keys.push([current.key, current.value]);

Then when you finished processing each objects you should be able to dump a json out of the js object. 然后,当您完成每个对象的处理后,您应该能够从js对象中转储一个json。

Duplicate keys aren't allowed in json, so what you're asking won't be supported by most json parsers. json中不允许使用重复键,因此大多数json解析器均不支持您要求的内容。

But you can write your own json formatter to do what you want. 但是您可以编写自己的json格式化程序以执行所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM