0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Loïc Faure-Lacroix for ur valuable time..What i have to do to get ur second output..Guide me to get the output..
It should be easy to figure out.
please guide me to achieve that..Also without changing my table format.
i am very new to this json API node.js.. I understood ur concept..Can you give some code base,so that i can get start from there.. Ca you also give idea about ur first output.. First output i think suits for me..SO please share that idea..
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.