0

I am trying to dynamically build some json based on data I retrieve from a database. Up until the opening '[' is the "root" I guess you could say. The next parts with name and value are dynamic and will be based on the number of results I get from the db. I query the db and then the idea was to iterate through the result adding to the json. Can I use jsonBuilder for the root section and then loop with jsonSlurper to add each additional section? Most of the examples I have seen deal with a root and then a one time "slurp" and then joining the two so wasn't sure if I should try a different method for looping and appending multiple sections.

Any tips would be greatly appreciated. Thanks.

    {
       "hostname": "$hostname",
       "path": "$path",
       "extPath": "$extPath",
       "appName": "$appName",
       "update": {"parameter":    [
                {
             "name": "$name",
             "value": "$value"
          },
                {
             "name": "$name",
             "value": "$value"
          }
       ]}
    }

EDIT: So what I ended up doing was just using StringBuilder to create the initial block and then append the subsequent sections. Maybe not the most graceful way to do it, but it works!

    //Create the json string
    StringBuilder json = new StringBuilder("""{
       "hostname": "$hostname",
       "path": "$path",
       "extPath": "$extPath",
       "appName": "$appName",
       "update": {"parameter":    ["""
    ) 


    //Append
    sql.eachRow("""<query>""",
    { params ->
    json.append("""{ "name": "params.name", "value": "params.value" },""");
    }
    ) 

    //Add closing json tags
    json.append("""]}}""")

2 Answers 2

2

If I got your explanation correctly and if the data is not very big (it can live in memory), I'd build a Map object (which is very easy to work with in groovy) and convert it to JSON afterwards. Something like this:

def data = [
    hostname: hostname,
    path: path,
    extPath: extPath,
    appName: appName,
    update: [parameter: []]
]

sql.eachRow(sqlStr) { row ->
  data.update.parameter << [name: row.name, value: row.value]
}

println JsonOutput.toJson(data)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion.
0

If you're using Grails and Groovy you can utilize grails.converters.JSON.

First, define a JSON named config:

JSON.createNamedConfig('person') {
    it.registerObjectMarshaller(Person) {
        Person person ->
        def output = [:]
        output['name'] = person.name
        output['address'] = person.address
        output['age'] = person.age
        output
    }
}

This will result in a statically defined named configuration for the Object type of person. Now, you can simply call:

JSON.use('person') {
    Person.findAll() as JSON
}

This will return every person in the database with their name, address and age all in one JSON request. I don't know if you're using grails as well in this situation though, for pure Groovy go with another answer here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.