r - 使用 purrr 或 rlist 从 json 文件中查找元素
问题描述
我有一个层次很深的 JSON 文件(例如https://raw.githubusercontent.com/APSIMInitiative/ApsimX/master/Models/Resources/Wheat.json)
# read data
library(jsonlite)
m <- read_json('https://raw.githubusercontent.com/APSIMInitiative/ApsimX/master/Models/Resources/Wheat.json')
我想找到一个 Name == "PotentialBranchingRate" 的元素。
{
"$type": "Models.Functions.PhaseLookup, Models",
"Name": "PotentialBranchingRate",
"Children": [...]
}
预期结果是返回 的父节点"Name": "PotentialBranchingRate"
。
List of 2
$ $type: chr "Models.Functions.PhaseLookup, Models"
$ Name : chr "PotentialBranchingRate"
$ Children : list ...
我搜索了 rlist 和 purrr 包中的函数,但找不到任何方法。
有什么建议可以解决这个问题吗?
解决方案
library(data.tree)
x <- as.Node(m)
Traverse(x, filterFun = function(.)
identical(GetAttribute(., "Name"), "PotentialBranchingRate")
)
#> [[1]]
#> levelName
#> 1 2
#> 2 °--Children
#> 3 ¦--1
#> 4 ¦ °--Children
#> 5 ¦ °--1
#> 6 ¦ °--Children
#> 7 ¦ °--1
#> 8 ¦ ¦--X
#> 9 ¦ ¦--Y
#> 10 ¦ °--Children
#> 11 °--2
#> 12 °--Children
#> 13 °--1
#> 14 °--Children
#>
#> [[2]]
#> levelName
#> 1 1
#> 2 °--Children
#> 3 °--1
#> 4 ¦--X
#> 5 ¦--Y
#> 6 °--Children
res <- .Last.value
lapply(res, function(.) jsonlite::prettify(rjson::toJSON(as.list(.))))
#> [[1]]
#> {
#> "$type": "Models.Functions.PhaseLookup, Models",
#> "Enabled": true,
#> "IncludeInDocumentation": true,
#> "Name": "PotentialBranchingRate",
#> "ReadOnly": false,
#> "Children": {
#> "1": {
#> "$type": "Models.Functions.PhaseLookupValue, Models",
#> ....
#>
#> ....... (truncated output for clarity)
#>
#> [[2]]
#> {
#> "$type": "Models.Functions.LinearInterpolationFunction, Models",
#> "Enabled": true,
#> "IncludeInDocumentation": true,
#> "Name": "PotentialBranchingRate",
#> "ReadOnly": false,
#> "XProperty": "[Structure].LeafTipsAppeared",
#> "Children": {
#> "1": {
#> "$type": "Models.Functions.XYPairs, Models",
#> "Enabled": true,
#> "IncludeInDocumentation": true,
#> "Name": "XYPairs",
#> "ReadOnly": false,
#> "X": {
#> "1": 1,
#> "2": 2,
#> "3": 3,
#> "4": 4,
#> "5": 5,
#> "6": 6,
#> "7": 7,
#> "8": 8
#> },
#> "Y": {
#> "1": 0,
#> "2": 0,
#> "3": 1,
#> "4": 2,
#> "5": 4,
#> "6": 7,
#> "7": 12,
#> "8": 20
#> },
#> "Children": [
#>
#> ]
#> }
#> }
#> }
#>
由reprex 包(v0.2.1)于 2019 年 2 月 21 日创建
推荐阅读
- c++ - 对象在通过时重置
- python - Pyinstaller,Windows 10 上的错误
- ios - iOS:如何在目标 C 中使用我的 swift 类中的特定功能?`使用未声明的标识符'NetworkClient'`
- asp.net-core - 无法在 .Net Core 应用程序中获取环境
- windows - 如何将 Go 程序作为服务运行
- javascript - React 如何保持组件状态?
- java - 无法将 openliberty、JPA 与 Hibernate 集成
- android - 图片模式下进入图片时如何不分离任务
- java - Android Studio 使用官方代码片段获取广告 ID
- javascript - 显示 CSS-Class 选择的 X div 中的随机 div