Skip to content

Conversation

cgiachalis
Copy link

This PR extends jsonString R6 constructor with an option ordered_json to preserve the insertion order of object keys using the type nlohmann::ordered_json from the vendor library. For convenience, a new R6 class ojsonString was added which represents an ordered_json type and inherits from jsonString.

For reference: Order of object keys and object order.

Example using ordered_json to preserve the insertion order:

j <- "{\"Jan\":1,\"Feb\":2,\"Mar\":3}"

# default case
jsonString$new(j, ordered_json = FALSE)

{
    "Feb": 2,
    "Jan": 1,
    "Mar": 3
}

# preserve order
jsonString$new(j, ordered_json = TRUE)

{
    "Jan": 1,
    "Feb": 2,
    "Mar": 3
}

# ojsonString always preserves order
ojsonString$new(j)

{
    "Jan": 1,
    "Feb": 2,
    "Mar": 3
}

Code Changes:

At C++ level, I created a new Rcpp class oJsonString to represent the ordered_json type. Practically, it is a replication of what has been done with JsonString Rcpp class with a minor code modification in addProperty method where I use the emplace_back and not emplace method because it couldn't compile.

At R level, the R6 constructor gets a new option ordered_json to select between preserving the order or not (default).

Internally, using the ordered_json argument we can switch to the appropriate Rcpp class JsonString or oJsonString at initialisation.

For user's convience, a new R6 class ojsonString was added as a wrapper that simply inherits from jsonString and defaults to ordered_json.

In addition, a new private state variable .is_ordered_json is introduced intended for methods that need to inherit the json type i.e., when using copy, unflatten , update etc.

Also, I added a private method getPtr() to abstract away a common pattern found across methods; and extend it a bit to guard against mixing json types . e.g., when adding a property from default json type to ordered json will raise an error. See below :

jstring <- jsonString$new("{\"a\":[1,2,3],\"b\":\"hello\"}") # json
ppty <- ojsonString$new("{\"f\":\"hello\"}")                 # ordered_json

jstring$addProperty("v1", ppty) # Error
jstring$merge(ppty)             # Error

Lastly, jsonString R6 interface has two new read only active fields: json_type and is_ordered_json.

Notes

  • I am working on some unit tests for ojsonString that can be used for jsonString too

  • Is it worth adding an abstract R6 base class so that both ojsonString and jsonString to inherit from?

closes #1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FR] - Option to preserve the insertion order

1 participant