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

Accessing array inside array syntax? #2151

Closed
duojet2ez opened this issue May 30, 2020 · 9 comments
Closed

Accessing array inside array syntax? #2151

duojet2ez opened this issue May 30, 2020 · 9 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@duojet2ez
Copy link

Hello,

I have a json file containing the following:

{
	 "cars": [
    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
    { "name":"BMW", "models":[ "320", "X3", "X5" ] },
    { "name":"Fiat", "models":[ "500", "Panda" ] }
		   ]
}

How would I go about accessing an array inside an array in my main.cpp file? For example if I wanted to create a sting variable and set "Fiesta" to it. Would I read into the file, declare a json object (j), and then... from here I can only guess as what the syntax would be. j[0].models[0] ??

One more question is what if the json object is an array containing multiple types (string, int, bool). Would I declare a vector of type j for the json object in my cpp file?

My apologies if this is covered in the documentation. I can't seem to figure it out.

@dota17
Copy link
Contributor

dota17 commented May 30, 2020

j["cars"] =

[    
    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
    { "name":"BMW", "models":[ "320", "X3", "X5" ] },
    { "name":"Fiat", "models":[ "500", "Panda" ] }
]

j["cars"][0] =

{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }

j["xars"][0][models] =

[ "Fiesta", "Focus", "Mustang"]

j["xars"][0][models][0] =

"Fiesta"

you just need to declare a nlohmann::json type variable j, it can accept any kind of JSON type value(e.g. object, array, string, bool, null, number)

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label May 30, 2020
@duojet2ez
Copy link
Author

Thank you!! This is exactly what I needed!!!! Thanks for clearing up the syntax

@Lightningblade
Copy link

Lightningblade commented May 10, 2022

json input

{
    "tag": "CARL A",
    "isin": "DK0010181676",
    "shares": 33699252,
    "name": "Carlsberg Breweries A/S",
    "url": "https://www.carlsberggroup.com/",
    "market": "Nasdaq Copenhagen",
    "sector": "Food, Beverage and Tobacco",
    "segment": "Large",
    "trades": [
        {
            "time": "2012-10-31T08:01:00Z",
            "price": 527,
            "amount": 35,
            "buyer": "DDB",
            "seller": "NDA",
            "seq": 1,
            "code": 0
        },
        {
            "time": "2012-10-31T08:30:00Z",
            "price": 512,
            "amount": 100,
            "buyer": "DDB",
            "seller": "DDB",
            "seq": 2,
            "code": 0
        }
    ]
}

Accessing the trades gives me as expected:

[
    {
        "amount": 35,
        "buyer": "DDB",
        "code": 0,
        "price": 527,
        "seller": "NDA",
        "seq": 1,
        "time": "2012-10-31T08:01:00Z"
    },
    {
        "amount": 100,
        "buyer": "DDB",
        "code": 0,
        "price": 512,
        "seller": "DDB",
        "seq": 2,
        "time": "2012-10-31T08:30:00Z"
    }
]

However iterating over j["trades"] via for (auto &trade : jsontrades) loops once with

{
    "amount": 35,
    "buyer": "DDB",
    "code": 0,
    "price": 527,
    "seller": "NDA",
    "seq": 1,
    "time": "2012-10-31T08:01:00Z"
}

and null together with an error:

terminate called after throwing an instance of 'nlohmann::detail::type_error'
  what():  [json.exception.type_error.302] type must be string, but is null

What am I doing wrong?

@gregmarr
Copy link
Contributor

@Lightningblade Can you provide a full example that reproduces the issue?

@Lightningblade
Copy link

main

    const char* FILEPATH = R"(TEST.json)";
    JsonParser jsonParser = JsonParser(FILEPATH);

    StockTradeHistory stockTradeHistory = StockTradeHistory(jsonParser);

stocktradehistory.cpp

StockTradeHistory::StockTradeHistory(JsonParser &input) {
    tag = input.j["tag"];
    isin = input.j["isin"];
    shares = input.j["shares"];
    name = input.j["name"];
    url = input.j["url"];
    market = input.j["market"];
    sector = input.j["sector"];
    segment = input.j["segment"];


    auto jsontrades = input.j["trades"];

    for (auto &trade : jsontrades) {

        Trade t;

        auto timestamp = trade["timestamp"];

        t.transactionTime = timestamp;

        t.price = trade["price"];
        t.amount = trade["amount"];
        t.buyer = trade["buyer"];
        t.seller = trade["seller"];
        t.seq = trade["seq"];
        t.code = trade["code"];

        trades.push_back(t);
    }
}

stocktradehistory.h

class StockTradeHistory {

public: StockTradeHistory(JsonParser &input);
    std::string tag;
    std::string isin;
            int shares;
    std::string name;
    std::string url;
    std::string market;
    std::string sector;
    std::string segment;

    std::vector<Trade> trades;

private: void AggregateTrades(JsonParser &input);
};

Trade is just a simple class with the 7 values.

And trades is a simple vector defined in the .h file.

@gregmarr
Copy link
Contributor

Your JSON has time but you're accessing timestamp.

@Lightningblade
Copy link

Thank you very much. I literally sat at this problem for two days.

@nlohmann
Copy link
Owner

Casual reminder that you can define JSON_DIAGNOSTICS before including the library to get extended diagnostic messages which can help to better locate the error.

1 similar comment
@nlohmann
Copy link
Owner

Casual reminder that you can define JSON_DIAGNOSTICS before including the library to get extended diagnostic messages which can help to better locate the error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

5 participants