Skip to content

Retrieve all values that match a json path #743

Closed

Description

Assuming that my json file is the following, I would like to collect all values that match with a regular expression using json_pointer. How can I get all values (integers) in the path /array/a/*?

I have used flatten() so far, that gives the "keys". But I don't know if I can query the json object to return an array of values that "match" a json path.

{
 "array": [
    {
      "a": 1,
      "b": [10,11,12]
    },
    {
      "a": 2,
      "b": [20,21,22]
    },
    {
      "a": 3,
      "b": [30,31,32]
    }
  ],
  "cost": 1
}

Activity

  1. nlohmann commented on Sep 14, 2017

    @nlohmann
    Owner

    What about

    #include "json.hpp"
    #include <iostream>
    #include <regex>
    
    using json = nlohmann::json;
    
    int main(int argc, char const *argv[])
    {
      json j = R"({
        "array": [
        {
          "a": 1,
          "b": [10,11,12]
        },
        {
          "a": 2,
          "b": [20,21,22]
        },
        {
          "a": 3,
          "b": [30,31,32]
        }
        ],
        "cost": 1
      })"_json;
    
      auto f = j.flatten();
    
      std::smatch sm;
      std::regex re("/array/[^/]+/a");
    
      json result;
    
      for (auto it = f.begin(); it != f.end(); ++it)
      {
        std::regex_search(it.key(), sm, re);
        if(not sm.empty())
        {
          result.push_back(it.value());
        }
      }
    
      std::cout << result << std::endl;        
    }
  2. nlohmann commented on Sep 14, 2017

    @nlohmann
    Owner

    No, but you must admit that this is a very specific usecase... And I think you could clean up the code above and use some <algorithm> magic.

  3. nlohmann commented on Sep 14, 2017

    @nlohmann
    Owner

    I don't know, maybe something like std::copy_if.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions