I am developing an Rest API using node.js + postgis.In that my problem is in formatting the result
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.
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.
Duplicate keys aren't allowed in json, so what you're asking won't be supported by most json parsers.
But you can write your own json formatter to do what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.