bim / json-to-table
JSONPath 实现用于查询和更新 JSON 对象,支持将 JSON 展平到表格
2.5
2021-08-07 19:01 UTC
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: ~4.0
- sami/sami: >=3.3.0
- satooshi/php-coveralls: >=1.0.1
This package is auto-updated.
Last update: 2024-09-08 01:50:23 UTC
README
这是一个用于 PHP 的 JSONPath 实现。
此实现包含规范中除 ()
运算符外的所有元素(规范中有 $..a[(@.length-1)]
,但可以使用 $..a[-1]
实现,后者更简单)。
除此之外,它还实现了一些扩展功能
- 正则表达式匹配比较(例如
$.store.book[?(@.author =~ /.*Tolkien/)]
) - 对于子运算符
[]
,不需要用引号包围子名称(例如$.[store][book, bicycle]
),除非字段名称不是有效的 JavaScript 变量名称。 - 可以使用
.length
来获取字符串的长度、获取数组的长度以及检查节点是否有子节点。
特性
此实现具有以下特性
- 使用 JSONPath 字符串集将 JSON 树转换为平面表格。
JSONPath 示例
考虑以下 JSON
{ "store": {
"name":"My Store",
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95,
"available": true,
"authors": ["Nigel Rees"]
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99,
"available": false,
"authors": []
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99,
"available": true,
"authors": ["Nigel Rees"]
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99,
"available": false,
"authors": ["Evelyn Waugh", "J. R. R. Tolkien"]
}
],
"bicycle": {
"color": "red",
"price": 19.95,
"available": true,
"model": null,
"sku-number": "BCCLE-0001-RD"
},
"bicycleSet": [{
"color": "red",
"price": 19.95,
"available": true,
"model": null,
"sku-number": "BCCLE-0001-RD"
},{
"color": "green",
"price": 19.75,
"available": false,
"model": null,
"sku-number": "RCADF-0002-CQ"
}]
},
"authors": [
"Nigel Rees",
"Evelyn Waugh",
"Herman Melville",
"J. R. R. Tolkien"
],
"Bike models": [
1,
2,
3
]
}
JSONPath => 结果
[$.store.bicycle.price]
[$.store.name,$.store.bicycle.price,$.store.bicycle.sku-number]
[$.store.book[*].price,$.store.book[*].price,$.store.book[*].authors[*],$.store.book[*].title,$.store.name]
使用方法
$json = '{... your json as string ...}'; $jsonPath = '[$.your.jsonpath.1,$.your.jsonpath.2]'; $jsonObject = new JsonObject($json); $result = $jsonObject->getTable($jsonPath);