承接 softcreatr/jsonpath 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

softcreatr/jsonpath

Composer 安装命令:

composer require softcreatr/jsonpath

包简介

JSONPath implementation for parsing, searching and flattening arrays

README 文档

README

Build Latest Release MIT licensed Plant Tree Codecov branch

This is a JSONPath implementation for PHP that targets the de facto comparison suite/RFC semantics while keeping the API small, cached, and eval-free.

Highlights

  • PHP 8.5+ only, with enums/readonly tokens and no eval.
  • Works with arrays, objects, and ArrayAccess/traversables in any combination.
  • Unions cover slices/queries/wildcards/multi-key strings (quoted or unquoted); negative indexes and escaped bracket notation are supported.
  • Filters support path-to-path/root comparisons, regex, in/nin/!in, deep equality, RFC-style null existence/value handling, and literal-only short-circuiting (e.g., ?(true), ?(false), && false, || true).
  • Tokenized parsing with internal caching; lightweight manual runner to try bundled examples quickly.

Installation

Requires PHP 8.5 or newer.

composer require softcreatr/jsonpath:"^1.0"

Development

Useful commands:

composer exec phpunit
composer phpstan
composer cs

JSONPath Examples

JSONPath Result
$.store.books[*].author the authors of all books in the store
$..author all authors
$.store..price the price of everything in the store.
$..books[2] the third book
$..books[(@.length-1)] the last book in order.
$..books[-1:] the last book in order.
$..books[0,1] the first two books
$..books[title,year] multiple keys in a union
$..books[:2] the first two books
$..books[::2] every second book starting from first one
$..books[1:6:3] every third book starting from 1 till 6
$..books[?(@.isbn)] filter all books with isbn number
$..books[?(@.price<10)] filter all books cheaper than 10
$..books.length the amount of books
$..* all elements in the data (recursively extracted)

Expression syntax

Symbol Description
$ The root object/element (not strictly necessary)
@ The current object/element
. or [] Child operator
.. Recursive descent
* Wildcard. All child elements regardless their index.
[,] Array indices as a set
[start:end:step] Array slice operator borrowed from ES4/Python.
?() Filters a result set by a comparison expression (constant expressions like ?(true)/?(false) are allowed; unsupported/empty filters evaluate to an empty result)
() Uses the result of a comparison expression as the index

PHP Usage

Using arrays

<?php
require_once __DIR__ . '/vendor/autoload.php';

$data = ['people' => [
    ['name' => 'Sascha'],
    ['name' => 'Bianca'],
    ['name' => 'Alexander'],
    ['name' => 'Maximilian'],
]];

print_r((new \Flow\JSONPath\JSONPath($data))->find('$.people.*.name')->getData());

/*
Array
(
    [0] => Sascha
    [1] => Bianca
    [2] => Alexander
    [3] => Maximilian
)
*/

Using objects

<?php
require_once __DIR__ . '/vendor/autoload.php';

$data = json_decode('{"name":"Sascha Greuel","birthdate":"1987-12-16","city":"Gladbeck","country":"Germany"}', false);

print_r((new \Flow\JSONPath\JSONPath($data))->find('$')->getData()[0]);

/*
stdClass Object
(
    [name] => Sascha Greuel
    [birthdate] => 1987-12-16
    [city] => Gladbeck
    [country] => Germany
)
*/

Magic method access

The options flag JSONPath::ALLOW_MAGIC will instruct JSONPath when retrieving a value to first check if an object has a magic __get() method and will call this method if available. This feature is iffy and not very predictable as:

  • wildcard and recursive features will only look at public properties and can't smell which properties are magically accessible
  • there is no property_exists check for magic methods so an object with a magic __get() will always return true when checking if the property exists
  • any errors thrown or unpredictable behavior caused by fetching via __get() is your own problem to deal with
<?php

use Flow\JSONPath\JSONPath;

$myObject = (new Foo())->get('bar');
$jsonPath = new JSONPath($myObject, JSONPath::ALLOW_MAGIC);

Script expressions

Script execution is intentionally not supported:

  • It would require eval, which we avoid.
  • Behavior would diverge across languages and defeat having a portable expression syntax.

Supported filter/query patterns (200+ cases covered in the comparison suite):

[?(@._KEY_ _OPERATOR_ _VALUE_)]
  Operators: ==, =, !=, <>, !==, <, >, <=, >=, =~, in, nin, !in

Examples:
[?(@.title == "A string")]      // equality
[?(@.title = "A string")]       // SQL-style equals
[?(@.price < 10)]               // numeric comparisons
[?(@.title =~ /^a(nother)?/i)]  // regex
[?(@.title in ["A","B"])]       // membership
[?(@.title nin ["A"])]          // not in
[?(@.title !in ["A"])]          // alternate not in
[?(@.key == @.other)]           // path-to-path comparison
[?(@.key == $.rootValue)]       // root reference
[?(@)] or [?(@==@)]             // truthy/tautology
[?(@.length)]                   // existence checks
[?(@['weird-key']=="ok")]       // bracket-escaped keys and negative indexes

A full list of (un)supported filter/query patterns can be found in the JSONPath Comparison Cheatsheet.

Similar projects

FlowCommunications/JSONPath is the predecessor of this library by Stephen Frank

Other / Similar implementations can be found in the Wiki.

Changelog

A list of changes can be found in the CHANGELOG.md file.

License 🌳

MIT © 1-2.dev

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the ecologi project, you’ll be creating employment for local families and restoring wildlife habitats.

Contributors ✨

Sascha
Sascha Greuel
James
James Lucas
Fabian
Fabian Blechschmidt
Mikko
Mikko Pesari
warlof/
warlof
Sergey
Sergey G
Alexandru
Alexandru Pătrănescu
Oleg
Oleg Andreyev
Remy
Remy Suen
esomething/
esomething

softcreatr/jsonpath 适用场景与选型建议

softcreatr/jsonpath 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 37.15M 次下载、GitHub Stars 达 165, 最近一次更新时间为 2020 年 10 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 softcreatr/jsonpath 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 softcreatr/jsonpath 我们能提供哪些服务?
定制开发 / 二次开发

基于 softcreatr/jsonpath 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 37.15M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 166
  • 点击次数: 25
  • 依赖项目数: 42
  • 推荐数: 1

GitHub 信息

  • Stars: 165
  • Watchers: 5
  • Forks: 32
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-10-11