I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
For example
Input
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}
Output
{
"a":"b",
"c":["d","e"],
"f":"g"
}
The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
If possible, I'd like to do this without editing any library code
Think other than JSON parsing library. It's very simple Java Program using
String.split()
method that convert Json String intoMap<String, List<String>>
without using any library.Sample code:
output:
Thanks to Mike Elofson and Braj for helping me in the right direction. I only wanted to have the keys with multiple values become arrays so I had to modify the code a bit. Eventually I want it to work for nested JSON as well, as it currently assumes it is flat. However, the following code works for what I need it for at the moment.
As of today the
org.json
library version20170516
providesaccumulate()
method that stores the duplicate key entries intoJSONArray
Output:
{
"a":"b",
"c":["d","e"],
"f":"g"
}
In order to accomplish what you want, you need to create some sort of custom class since
JSON
cannot technically have 2 values at one key. Below is an example:You can then retrieve the values from the database, call the
.add(String key, Object o)
function with the column name from the database, and the value (as theObject
param). Then call.toJson()
when you are finished.