Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance operation on untyped json through operator overload based on json pointer #1003

Closed
wants to merge 3 commits into from

Conversation

lymslive
Copy link

Although it is wonderfull to deserilize json to strong type struct, sometimes it has to deal with untyped json, especially when the input json is too loose or too freely to fit a struct hierarchy. So I devolop a solution for such case.

I summarize the following basic operation on untyped json tree:

  1. Locate and refer to some node in the tree by json pointer syntax, using operator / overload.
  2. Read value from leaf node with default fallback, using operator |, image as get_or method.
  3. Write value to json node as container of common data type, using operator <<, image as push item to array or object, or overwrite put value to scalar node.
  4. Some advanced modification on json tree as a whole, using operator |, pipe to function or closure.

All the operators above can be chained as return json pointer, except case 2 which only return primitive scalar value.

Example from that added to README.md:

let v: Value = json( {
        "name": "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567",
            "+44 2345678"
        ]
    });

let age_ptr = &v / "age";
let age_val = age_ptr | 0; // got 43, or default 0 if something wrong.
let first_phone = &v / "phones" / 0 | ""; // got &str
assert_eq!(first_phone, "+44 1234567");

// modify some node
let _ = &mut v / "age" << 44;
let _ = &mut v / "phones" << ["+44 3456789"];
let _ = &mut v << ("sex": "male");

And there is also fully documantation example and tests.

Because it is impossible to overload operator for serde_json::Value outside the crate, but at most can only to overload operator for new struct for json pointer. So I create this pull request to support json operator natively as well.

Copy link
Member

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the PR, but I would prefer not to support this mechanism in this library.

@dtolnay dtolnay closed this Mar 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants