【问题标题】:Getting the name of each field in JSON获取 JSON 中每个字段的名称
【发布时间】:2015-06-02 13:07:48
【问题描述】:

我正在尝试在 Grails 中解析一个随机 JSON 文件。

首先我需要获取每个字段的名称

例如下面给出的 JSON 文件,

{
    "abbreviation": "EX",
    "guid": "1209812-1l2kj1j-fwefoj9283jf-ae",
    "metadata": {
      "dataOrigin": "Example"
    },
    "rooms": 
    [
    ],
    "site": {
      "guid": "1209812-1l2kj1j-fwefoj9283jf-ae"
    },
    "title": "Example!!"
}

我想找出 JSON 文件的结构(可能是键列表),例如我想保存键列表,例如 'abbreviation'、'guid'、'metadata'、'rooms'、'此 JSON 文件中的 site', 'title'。

我该怎么做?

(我们需要键的名称才能获取该键的值,因此对于任意结构的 JSON 文件,我需要先找出键)

【问题讨论】:

  • new groovy.json.JsonSlurper().parse(path to the json file).keySet() 是我想你要找的。​​span>
  • 知道了,非常感谢!!

标签: json parsing grails


【解决方案1】:

你可以试试下面的代码

def filePath = "JSONFILE.json"
def text = new File(filePath).getText()
def json = JSON.parse(text)                     
def jsonKeys = json.collect{it.key}
println(jsonKeys)

这将打印所有 json 键

【讨论】:

    【解决方案2】:

    根据 dmahaptro 的评论,我知道如何获取 JSON 对象中的所有键。

    这是我为测试它而编写的一个简单示例代码

    String jsonFile = new JsonSlurper().parseText(new URL(path to the json file).text)
    JSONArray jsonParse = new JSONArray(jsonFile)
    
    int len = jsonParse.length()
    def names = []
    def keys = []
    (0..len-1).each {
        JSONObject val = jsonParse.getJSONObject(it)
        int numKeys = val.length()
        names = val.names()
        keys = val.keySet()
        (0..numKeys-1).each {
            def field = names[it]
            println field +" : " + val."${field}"
        }
    }
    

    这将打印给定 JSON 文件的键:值对。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2017-04-13
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多