Deep Pick은 수동 캐스팅이나 동적 타입이 필요 없도록 안전하고 타입 인식 가능한 JSON 파싱을 단순화하는 Dart 패키지입니다. 파싱에 실패했을 때 명확한 오류 메시지를 제공하는 깔끔하고 표현력 있는 API를 통해 중첩된 JSON 구조를 탐색할 수 있습니다. 유연한 입력 형식을 지원하면서 고정되고 예측 가능한 출력 형식을 보장하여, 복잡하거나 깊이 중첩된 JSON 데이터를 플랫폼 간에 신뢰성 있게 처리하는 데 이상적입니다.
사용 사례
깊이 중첩된 JSON 응답 분석
선택적 또는 누락된 JSON 필드 처리
안전하게 데이터 검증 및 추출하기
강력한 API 클라이언트 구축
외부 소스에서 동적 JSON 사용
데이터 모델 추출에서 반복 코드 줄이기
주요 기능
타입 안전한 JSON 접근
포괄적인 오류 메시지
유연한 입력 처리
'dynamic' 의존 없음
선택적 값에 대한 지원
중첩 경로를 위한 메서드 체이닝
적합한 대상
REST API를 사용하는 개발자
코드 안정성을 우선시하는 팀
신뢰할 수 있는 JSON 파싱이 필요한 프로젝트
복잡한 데이터 모델을 가진 앱
Flutter를 사용하는 프론트엔드 개발자
잘못된 캐스트로 인한 런타임 오류를 피하는 사람들
고려 사항
경로 기반 탐색에 대한 이해가 필요합니다
간단한 경우에 약간의 오버헤드가 추가될 수 있습니다
JSON 유사 구조에 한정
JSON이 아닌 데이터 형식에는 적합하지 않습니다
명확한 데이터 스키마와 함께 사용할 때 가장 효과적입니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
deep_pick
Simplifies manual JSON parsing with a type-safe API.
This example demonstrates parsing of an HTTP response using deep_pick. You can either use it to parse individual values of a json response or parse whole objects using the fromPick constructor.
final response = await http.get(Uri.parse('https://api.countapi.xyz/stats'));
final json = jsonDecode(response.body);
// Parse individual fields (nullable)finalint? requests = pick(json, 'requests').asIntOrNull();
// Require values to be non-null or throw a useful error messagefinalint keys_created = pick(json, 'keys_created').asIntOrThrow();
// Pick deep nested values without parsing all objects in betweenfinalString? version = pick(json, 'meta', 'version', 'commit').asStringOrNull();
// Parse a full object using a fromPick factory constructorfinalCounterApiStats stats = CounterApiStats.fromPick(pick(json).required());
// Parse lists with a fromPick constructor finalList<CounterApiStats> multipleStats = pick(json, 'items')
.asListOrEmpty((pick) => CounterApiStats.fromPick(pick));
Returns the picked Object as String representation.
It doesn't matter if the value is actually a int, double, bool or any other Object.
pick calls the objects toString method.
pick tries to parse Strings with int.tryParse and double.tryParse.
A int can be parsed as double (no precision loss) but not vice versa because it could lead to mistakes.
Replacing the static function with a factory constructor doesn't work.
Constructors cannot be referenced as functions, yet (dart-lang/language/issues/216).
Meanwhile, use .asListOrEmpty((it) => Person.fromPick(it)) when using a factory constructor.
Note 2
pick called in the fromPick function uses the parameter pick, not the top-level function.
This is possible because Pick implements the .call() method.
This allows chaining indefinitely on the same Pick object while maintaining internal references for useful error messages.
Both versions produce the same result and shows you're not limited to 10 arguments.
Picking the Map is rarely used, because Pick itself grants further picking using the .call(args) method.
Converting back to a Map is usually only used for existing fromMap mapper functions.
Parsers in deep_pick are based on extension functions on the classes Pick.
This makes it flexible and easy for 3rd-party types to add custom parsers.
This example parses a int as Firestore Timestamp.
import'package:cloud_firestore/cloud_firestore.dart';
import'package:deep_pick/deep_pick.dart';
extensionTimestampPickonPick {
TimestampasFirestoreTimeStampOrThrow() {
final value = required().value;
if (value isTimestamp) {
return value;
}
if (value isint) {
returnTimestamp.fromMillisecondsSinceEpoch(value);
}
throwPickException("value $value at $debugParsingExit can't be casted to Timestamp");
}
Timestamp? asFirestoreTimeStampOrNull() {
if (value == null) returnnull;
try {
returnasFirestoreTimeStampOrThrow();
} catch (_) {
returnnull;
}
}
}
let
When using a custom type in only a few places, it might be overkill to create all the extensions.
For those cases use the let function borrowed from Kotlin to creating neat one-liners.
Picking values from a Firebase DocumentSnapshot is usually very selective.
Only a fraction of the properties have to be parsed.
In this scenario it would be overkill to map the whole document to a Dart object.
Instead, parse the values in place while staying type-safe.
Use .asStringOrThrow() when confident that the value is never null and always exists.
The return type then becomes non-nullable (String instead of String?).
When the data doesn't contain the full_name field (against your assumption) it would crash throwing a PickException.
finalDocumentSnapshot userDoc =
awaitFirebaseFirestore.instance.collection('users').doc(userId).get();
final data = userDoc.data();
finalString fullName = pick(data, 'full_name').asStringOrThrow();
finalString? level = pick(data, 'level').asIntOrNull();
deep_pick offers an alternative required() API with the same result.
This is useful to make sure a value exists before parsing it.
In case it is null or absent a useful error message is printed.
Before Dart 2.12 and the new ?[] operator one had to write a lot of code to prevent crashes when a value isn't set!
Reducing this boilerplate was the origin of deep_pick.
String milestoneCreator;
final milestone = json['milestore'];
if (milestone != null) {
final creator = json['creator'];
if (creator != null) {
final login = creator['login'];
if (login isString) {
milestoneCreator = login;
}
}
}
print(milestoneCreator); // octocat
This example of parses an issue object of the GitHub v3 API.
Today with Dart 2.12+ parsing Dart data structures has become way easier with the introduction of the ?[] operator.
final json = jsonDecode(response.data);
final milestoneCreator = json?['milestone']?['creator']?['login'] asString?;
print(milestoneCreator); // octocat
deep_pick backports this short syntax to previous Dart versions (<2.12).
final milestoneCreator = pick(json, 'milestone', 'creator', 'login').asStringOrNull();
print(milestoneCreator); // octocat
Still better than vanilla
But even with the latest Dart version, deep_pick offers fantastic features over vanilla parsing using the ?[] operators:
1. Flexible input types
Different languages and their JSON libraries generate different JSON.
Sometimes ids are String, sometimes int. Booleans are provided as true or with quotes as String "true".
The meaning is the same but from a type perspective they are not.
deep_pick does the basic conversions automatically.
By requesting a specific return type, apps won't break when a "price" usually returns double (0.99) but for whole numbers int (1 instead of 1.0).
Using the ?[] operator can crash for Lists.
Accessing a list item by index outside of the available range causes a RangeError.
You can't access index 23 when the List has only 10 items.
json['shoes']?[23]?['id'] asString?;
// Unhandled exception:// RangeError (index): Invalid value: Not in inclusive range 0..10: 23
pick automatically catches the RangeError and returns null.
Vanilla Dart returns a type error because null is not a String.
There is no information available which part is null or missing.
final milestoneCreator = json?['milestone']?['creator']?['login'] asString;
// Unhandled exception:// type 'Null' is not a subtype of type 'String' in type cast
deep_pick shows the exact location where parsing failed, making it easy to report errors to the API team.
final milestoneCreator = pick(json, 'milestone', 'creator', 'login').asStringOrThrow();
// Unhandled exception:// PickException(// Expected a non-null value but location "milestone" in pick(json, "milestone" (absent), "creator", "login") is absent. // Use asStringOrNull() when the value may be null at some point (String?).// )
Notice the distinction between "absent" and "null" when you see such errors.
"absent" means the key isn't found in a Map or a List has no item at the requested index
"null" means the value at that position is actually null
4. Null is default, crashes intentional
Parsing objects from external systems isn't type-safe.
API changes happen, and it is up to the consumer to decide how to handle them.
Consumer always have to assume the worst, such as missing values.
It's so easy to accidentally cast a value to String in the happy path, instead of String? accounting for all possible cases.
Easy to write, easy to miss in code reviews.
Forgetting that null could be a valid return type results in a type error:
json?['milestone']?['creator']?['login'] asString;
// ----^// Unhandled exception:// type 'Null' is not a subtype of type 'String' in type cast
With deep_pick, all casting methods (.as*()) have null in mind.
For each type you have to choose between at least two ways to deal with null.
Having "Throw" and "Null" in the method name, clearly indicates the possible outcome in case the values couldn't be picked.
Throwing is not a bad habit, some properties are essential for the business logic and throwing an error the correct handling.
But throwing should be done intentional, not accidental.
5. Map Objects with let
Even with the new ?[] operator, mapping a value to a new Object (i.e. when wrapping it in a domain Object) can't be done in a single line.
final value = json?['id'] asString?;
finalUserId id = value == null ? null : UserId(value);
deep_pick borrows the let function from Kotlin creating a neat one-liner
finalUserId id = pick(json, 'id').letOrNull((it) => UserId(it.asString()));
License
Copyright2019PascalWelschLicensed under the ApacheLicense, Version2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unlessrequired by applicable law or agreed to in writing, software
distributed under the Licenseis distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Licensefor the specific language governing permissions and
limitations under the License.