json_path는 JSONPath에 대한 RFC 9535를 구현한 Dart 패키지로, JSON 데이터에 대한 강력한 쿼리 및 조작을 가능하게 합니다. `$.store.book[2].price`와 같은 표현력 있는 경로 식을 사용하여 파싱된 JSON 객체의 값을 읽고 쓸 수 있습니다. 이 패키지는 표준 JSONPath 문법을 지원하며 Android, iOS, Web, macOS, Windows, Linux 등 여러 플랫폼에서 호환됩니다. Flutter 애플리케이션에서 동적 데이터 추출 및 변환에 이상적입니다.
사용 사례
중첩된 JSON 값 추출
특정 JSON 필드 업데이트
JSON 데이터에서 배열 필터링
복잡한 JSON 구조 분석
동적 구성 처리
API에서의 데이터 변환
주요 기능
RFC 9535 완전 준수
읽기 및 쓰기 작업을 지원합니다
직관적인 경로 구문 예: `$.store.book[2].price`
크로스 플랫폼 호환성
경량이고 빠름
강력한 오류 처리
적합한 대상
동적 JSON 쿼리가 필요한 Flutter 앱
백엔드 서비스가 JSON 페이로드 처리 중
구성 관리 시스템
변동하는 응답 구조를 가진 API 클라이언트
유연한 JSON 조작을 필요로 하는 데이터 파이프라인
고려 사항
유효한 JSON 입력이 필요합니다
깊이 중첩되거나 큰 JSON일 경우 성능이 달라질 수 있습니다
RFC 9535에 정의된 JSONPath 구문에 한정
JSON이 아닌 데이터 유형에는 적합하지 않습니다
신뢰할 수 없는 입력에서는 신중한 검증이 필요할 수 있습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
RFC 9535 - JSONPath: Query Expressions for JSON in Dart
JSONPath defines a string syntax for selecting and extracting JSON (RFC 8259) values from within a given JSON value.
This library is a Dart implementation of the RFC 9535 JsonPath specification. It is also expected to pass the latest version
of the Compliance Test Suite. If you find a missing or incorrectly implemented feature, please open an issue.
For installation instructions and a detailed API documentation, see the pub.dev page.
Usage example:
import'dart:convert';
import'package:json_path/json_path.dart';
voidmain() {
final json = jsonDecode('''
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
''');
final prices = JsonPath(r'$..price');
print('All prices in the store:');
/// The following code will print:////// $['store']['book'][0]['price']: 8.95/// $['store']['book'][1]['price']: 12.99/// $['store']['book'][2]['price']: 8.99/// $['store']['book'][3]['price']: 22.99/// $['store']['bicycle']['price']: 19.95
prices
.read(json)
.map((match) => '${match.path}:\t${match.value}')
.forEach(print);
}
Data manipulation
Each JsonPathMatch produced by the .read() method contains the .pointer property which is a valid JSON Pointer
and can be used to alter the referenced value. If you only need to manipulate JSON data,
check out my JSON Pointer implementation.
User-defined functions
The JSONPath parser may be extended with user-defined functions. The user-defined functions
take precedence over the built-in ones specified by the standard. Currently, only
functions of 1 and 2 arguments are supported.
To create your own function:
Import package:json_path/fun_sdk.dart.
Create a class implementing either Fun1 (1 argument) or Fun2 (2 arguments).
To use it:
Create a new JsonPathParser with your function: final parser = JsonPathParser(functions: [MyFunction()]);
Parse the expression: final jsonPath = parser.parse(r'$[?my_function(@)]');
For more details see the included example.
This package comes with a few non-standard functions which you might find useful.
count(<NodeList>) - returns the number of nodes selected by the argument
index(<SingularNodeList>) - returns the index under which the array element is referenced by the parent array
key(<SingularNodeList>) - returns the key under which the object element is referenced by the parent object
is_array(<Maybe>) - returns true if the value is an array
is_boolean(<Maybe>) - returns true if the value is a boolean
is_number(<Maybe>) - returns true if the value is a number
is_object(<Maybe>) - returns true if the value is an object
is_string(<Maybe>) - returns true if the value is a string
reverse(<Maybe>) - returns the reversed string
siblings(<NodeList>) - returns the siblings for the nodes
xor(<bool>, <bool>) - returns the XOR of two booleans arguments
To use them, import package:json_path/fun_extra.dart and pass the functions to the JsonPath() constructor:
final jsonPath = JsonPathParser(functions: [
constKey(),
constReverse(),
]).parse(r'$[?key(@) == reverse(key(@))]');