如何从JSON字符串中获取特定值

时间:2017-01-06 16:24:47

标签: json grails groovy

我有一个如下的JSON字符串:

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

我正在解析它如下:

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

我想在不同变量中为accesskeybucketname放置foobar的值

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

我尝试了以下似乎不起作用的内容:

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"]
    }
}

1 个答案:

答案 0 :(得分:0)

您的json字符串不好,您需要凭据和名称之间的逗号。 使用它的GroovyConsole显示了如何处理元素。

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}"