简体   繁体   中英

How to get a specific value from a JSON string

I have a JSON string like below:

{
 "VCAP_SERVICES": {
    "amazon-s3": [
       {
         "credentials": {
              "accesskey": "somevalue",
              "bucketname": "somevalue1"
          }
          "name": "foo"
       },
       {
         "credentials": {
              "accesskey": "someothervalue",
              "bucketname": "someothervalue1"
          }
          "name": "bar"
        }
    ]
  }
}

I'm parsing it as below:

import org.codehaus.groovy.grails.web.json.JSONObject
import grails.converters.JSON
JSONObject myJson = JSON.parse(myString)

I would like to place values for accesskey and bucketname for both foo and bar in different variables

def foo_accesskey = null
def foo_bucketname = null
def bar_accesskey = null
def bar_bucketname = null

I tried the following which doesn't seem to be working:

myJson["amazon-s3"].each {id, data -> 
    if (id == "foo") {
        foo_accesskey = myJson["amazon-s3"]["credentials"]["accesskey"]
        foo_bucketname = myJson["amazon-s3"]["credentials"]["bucketname"]
    }
    else if (id == "bar") {
        bar_accesskey = myJson["amazon-s3"]["credentials"]["accesskey"]
        bar_bucketname = myJson["amazon-s3"]["credentials"]["bucketname"]
    }
}

Your json string is bad, you need a comma between credentials and name. GroovyConsole using this shows how to address your elements.

def jsonStr = '{"VCAP_SERVICES": {"amazon-s3": [{"credentials": {"accesskey": "somevalue","bucketname": "somevalue1"},"name": "foo"},{"credentials": {"accesskey": "someothervalue","bucketname": "someothervalue1"},"name": "bar"}]}}'

def json = grails.converters.JSON.parse(jsonStr)
println json.toString()
println "-----"
def foo_ac
def foo_bu
def bar_ac
def bar_bu
json.VCAP_SERVICES."amazon-s3".each {
    println "it: ${it}"
    println "-----"
    if (it.name == 'foo') {
        foo_ac = it.credentials.accesskey
        foo_bu = it.credentials.bucketname
    }
    if (it.name == 'bar') {
        bar_ac = it.credentials.accesskey
        bar_bu = it.credentials.bucketname
    }
}
println "foo_ac: ${foo_ac}"
println "foo bu: ${foo_bu}"
println "bar ac: ${bar_ac}"
println "bar bu: ${bar_bu}"

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