Skip to content

Filter JSON objects in a Array #2236

Answered by nlohmann
nyckmaia asked this question in Q&A
Discussion options

You must be logged in to vote

You can use any STL algorithm you like, e.g. std::copy_if:

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main()
{
    json j = R"({
    "myArray":
    [
        {
            "key": "A",
            "name": "John"
        },
        {
            "key": "B",
            "name": "Steve"
        },
        {
            "key": "A",
            "name": "Roger"
        }
    ]
})"_json;
    
    json filtered;
        std::copy_if(j["myArray"].begin(), j["myArray"].end(),
                     std::back_inserter(filtered), [](const json& item) {
                        return item.contains("key") && item["key"] == "A";
        });
    std::cout << filtered << std::…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@nyckmaia
Comment options

Answer selected by nyckmaia
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants