简体   繁体   中英

Transform JSON with Groovy

I have a JSON file:

def jsonTxt =
'''
{
    "fields": [
       "key1",
       "key2",
       "key3"
    ],
    "table": [
      [
        1,
        2,
        "three"
      ],
      [
       4,
       5,
       "six"
      ],
      [
       7,
       8,
       "nine"
      ]
    ] 
}     
'''     

Values in fields array are names (keys) for values in table array. I want to match them like this:

[
    {
        "key1": 1,
        "key2": 2,
        "key3": "three"
    },
    {
        "key1": 4,
        "key2": 5,
        "key3": "six"
    },
    {
        "key1": 7,
        "key2": 8,
        "key3": "nine"
    }
]

I tried with:

def result =  jsonSlurper.parseText(jsonTxt)

def myRes = result.table.collect {
     [
       key1 : it[0],
       key2 : it[1],
       key3 : it[2]
     ]  
}

And it returns what i expected. But how to avoid this hardcode? I mean, json property name I should take from fields and values for them like with increment indexes. If in the next JSON there will be another field, eg accountId instead of key1 or as additional field, my code will be not working correctly.

You can collect over the rows of the table and "zip" the header with the row and turn it into a map using transpose and collectEntries .

Eg

result.table.collect{
  [result.fields, it].transpose().collectEntries() 
}

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.

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