0

I am extremely new to c++, and I am trying to use jsoncpp to get the weather out of an array.

The json string looks like this:

{"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200}

Parsing the json array works fine, here is the relevant code:

Json::Value root;   
Json::Reader reader;
bool parsingSuccessful = reader.parse( data.c_str(), root );
if ( !parsingSuccessful )
{
    std::cout  << "Failed to parse"
    << reader.getFormattedErrorMessages();
    return 0;
}
std::cout << root.get("description", "n/a" ).asString() << std::endl;

But I still end up with n/a. I want to be able to access the "description" field in the "weather" array. How can I do this?

Chud37
  • 4,907
  • 13
  • 64
  • 116
  • The root doesn't have a "description" field. The first element in `root.get("weather")` should have it. – Frederik.L May 21 '16 at 07:51
  • @Frederik.L Yeah, I did try that. But then how do I specify "description" in "weather" specifically? – Chud37 May 21 '16 at 07:53
  • 1
    Not exactly the same use case, but check this: http://stackoverflow.com/questions/27902576/jsoncpp-find-object-in-array-by-matching-value – Frederik.L May 21 '16 at 08:19

1 Answers1

1

Does this work?

const Json::Value weather = root["weather"];
for ( int index = 0; index < weather.size(); ++index )
{
    std::cout << weather[index]["description"].asString();
}
Justin Lam
  • 789
  • 5
  • 8