feat: add operator[] access support for TJValue#45
Conversation
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
This PR introduces a chainable operator[] accessor API for TJValue to simplify JSON navigation by key and index, and adds tests validating the new behavior (including strict-mode missing-key throwing).
Changes:
- Added
TJValueAccessorandTJValue::operator[]overloads for key/index access with chainable.as<T>(). - Added
TJValue::as<T>()convenience alias forget<T>(). - Added unit tests covering key/index access and strict missing-key behavior.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| tests/testtinyjsonvaluesget.cpp | Adds tests for new operator[] / accessor chaining and strict-mode missing-key throwing. |
| src/TinyJSON.h | Adds TJValueAccessor, TJValue::operator[] overloads, and TJValue::as<T>(). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| template<typename T> | ||
| T as() const | ||
| { | ||
| if (_by_index) | ||
| { | ||
| auto value = get_value_ptr(); | ||
| if (value == nullptr) | ||
| { | ||
| return default_value<T>(); | ||
| } | ||
| return value->get<T>(); | ||
| } |
|
|
||
| const auto* object = dynamic_cast<const TJValueObject*>(_owner); | ||
| if (object != nullptr) | ||
| { |
| ASSERT_EQ(1, (*json)[0].as<int>()); | ||
|
|
|
Hi @njp2k5, Thank you so much for taking the time to implement this and writing such thorough unit tests! I saw the automated review here as well, and I really appreciate the depth of the work you put into resolving #44. Because this is a lightweight library, I want to avoid adding proxy accessor classes to keep the core footprint minimal. Your approach actually prompted me to jump in and implement a native operator[] design directly into the core types over in #46. I'm going to close this one in favour of that lightweight approach, but I sincerely appreciate your initiative and contribution here! |
|
Thanks for the thoughtful feedback and explanation! That makes sense — keeping the library lightweight is definitely a reasonable design goal here. I appreciate you taking the time to review the implementation and explain the direction taken in #46. Glad the tests and exploration were still useful, and I enjoyed working through the issue. |
Description
Adds support for ergonomic
json[key].as<T>()access syntax and uniform indexed access onTJValue.This introduces:
TJValue::as<T>()as an alias forget<T>()TJValue::operator[](const TJCHAR* key)TJValue::operator[](int index)Supported usage examples:
This implementation keeps the change minimal and localized to existing access behavior.
Fixes #44
New Package?
Version Bump?
Type of Change
How Has This Been Tested?
Added focused tests for:
as<T>()All tests pass locally:
Suggested Checklist: