首页 > 解决方案 > 遍历Json对象

问题描述

我有一个 json 文件,其中包含以下数据:

    {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

我需要在 pyspark 中读取这个文件并遍历 json 中的所有元素。我需要识别结构列的所有结构、数组和数组,并且需要为每个结构和数组列创建单独的配置单元表。

例如:

词汇表 将是一张以“标题”为列的表格

GlossEntry将是另一个包含“ID”、“SortAs”、“GlossTerm”、“acronym”、“abbrev”列的表

未来数据将随着更多的嵌套结构而增长。所以我将不得不编写一个通用代码,它遍历所有 JSON 元素并识别所有结构和数组列。

有没有办法遍历嵌套结构中的每个元素?

标签: jsonpyspark

解决方案


Spark 能够自动解析和推断 json 模式。一旦它在 spark 数据框中,您可以通过指定其路径来使用 json 访问元素。

json_df = spark.read.json(filepath)
json_df.printSchema()

输出:

root
 |-- glossary: struct (nullable = true)
 |    |-- GlossDiv: struct (nullable = true)
 |    |    |-- GlossList: struct (nullable = true)
 |    |    |    |-- GlossEntry: struct (nullable = true)
 |    |    |    |    |-- Abbrev: string (nullable = true)
 |    |    |    |    |-- Acronym: string (nullable = true)
 |    |    |    |    |-- GlossDef: struct (nullable = true)
 |    |    |    |    |    |-- GlossSeeAlso: array (nullable = true)
 |    |    |    |    |    |    |-- element: string (containsNull = true)
 |    |    |    |    |    |-- para: string (nullable = true)
 |    |    |    |    |-- GlossSee: string (nullable = true)
 |    |    |    |    |-- GlossTerm: string (nullable = true)
 |    |    |    |    |-- ID: string (nullable = true)
 |    |    |    |    |-- SortAs: string (nullable = true)
 |    |    |-- title: string (nullable = true)
 |    |-- title: string (nullable = true)

然后选择要提取的字段:

json_df.select("glossary.title").show()
json_df.select("glossary.GlossDiv.GlossList.GlossEntry.*").select("Abbrev","Acronym","ID","SortAs").show()

提取输出:

+----------------+
|           title|
+----------------+
|example glossary|
+----------------+

+-------------+-------+----+------+
|       Abbrev|Acronym|  ID|SortAs|
+-------------+-------+----+------+
|ISO 8879:1986|   SGML|SGML|  SGML|
+-------------+-------+----+------+

推荐阅读