Search code examples
c++jsonboost

How to know count of JSON objects in the file?


I have JSON file

    {
  "media": [
    {
      "id": 1234,
      "order": 1,

    },
    {
      "id": 1385,
      "order": 3,

    },
    {
      "id": 1289,
      "order": 2,

    }
  ]
}

with 3 blocks (objects) with the same fileds name ("id", "order"). In the presented example we have 3 blocks. I want to get 3 as answer for my request. How can I do it? If it possible, with the boost library. Next time I'll get another JSON file witch will contains 4 or 5 same blocks

{
  "id": 1234,
  "order": 1,
},

and I want to know count of those blocks in the JSON file


Solution

  • Simplest: Live On Compiler Explorer

    #include <boost/json/src.hpp>
    
    static auto sample = R"({
                "media": [{
                    "id": 1234,
                    "order": 1,
                },
                {
                    "id": 1385,
                    "order": 3,
    
                },
                {
                    "id": 1289,
                    "order": 2,
    
                }]
            })";
    
    int main() {
        auto v = boost::json::parse(sample, {}, {.allow_trailing_commas=true});
    
        return v.at("media").as_array().size();
    }
    

    Returns 3

    Note that there are much more efficient ways to do it using e.g. https://www.boost.org/doc/libs/1_79_0/libs/json/doc/html/json/ref/boost__json__stream_parser.html or even just https://www.boost.org/doc/libs/1_79_0/libs/json/doc/html/json/ref/boost__json__basic_parser.html