json - 遍历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 元素并识别所有结构和数组列。
有没有办法遍历嵌套结构中的每个元素?
解决方案
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|
+-------------+-------+----+------+
推荐阅读
- c++ - 如何在结构的`std::list`中搜索?
- angularjs - {$ ... $} 在 django 模板中代表什么?
- javascript - react 在同一页面下载文档
- azure - Azure 数据工厂中的 PATCH 请求
- rpa - 如何使用 Web Recorder 的“文件下载”命令下载需要认证的文件?
- java - 在浏览器中打开特定链接,而不是通过正则表达式打开 webview
- spring-boot - 如果 Header 本身不存在,我们想在 Camel 的 routeBuilder 中验证并继续
- powershell - 如何使用网络用户删除我的密码?
- javascript - 如何根据条件从数组中删除重复元素?
- flutter - 删除颤振警报对话框的灰色背景