rtfminc
rtfminc

Reputation: 6363

JSON with duplicate key names losing information when parsed

So either I go back and tell someone that they should fix their JSON, or I need to find out what I am doing wrong. Here is the JSON, notice that parameter occurs three times:

String j= '''{
    "jobname" : "test",
    "parameters" : {
    "parameter": {"name":"maxErrors", "value":"0"},
    "parameter": {"name":"case", "value":"lower"},
    "parameter": {"name":"mapTable", "value":"1"}
    }
} '''

And I am trying to get each name & value. My code

def doc = new JsonSlurper().parseText(j)
def doc1 = doc.entrySet() as List
def doc2 = doc.parameters.entrySet() as List
println "doc1.size===>"+doc1.size()
println "doc1===>"+doc1
println "doc2.size===>"+doc2.size()
println "doc2===>"+doc2

And my results:

doc1.size===>2
doc1===>[jobname=test, parameters={parameter={name=mapTable, value=1}}]
doc2.size===>1
doc2===>[parameter={name=mapTable, value=1}]

How come I only get one parameter? Where are the other two? It looks like JSON only keeps one parameter and discards the other ones.

Upvotes: 2

Views: 998

Answers (1)

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8401

The JSON is not in the correct format. There should not be duplicate key in the same hierarchy or they will override each other.

It should have been an array of paramters.

Like this,

String j= '''{
 "jobname" : "test",
 "parameters" : [
 {"name":"maxErrors", "value":"0"},
 {"name":"case", "value":"lower"},
 {"name":"mapTable", "value":"1"}
 ]
} 

Upvotes: 5

Related Questions