Skip to content

Instantly share code, notes, and snippets.

@andrewjkerr
Last active December 16, 2015 03:19
Show Gist options
  • Save andrewjkerr/5368600 to your computer and use it in GitHub Desktop.
Save andrewjkerr/5368600 to your computer and use it in GitHub Desktop.
This is a parsing example for the udp/json-parser which can be found here: (https://github.com/udp/json-parser.) This parser allows for easy parsing of a JSON file in C++. --- The sample JSON file is an example using the old Facebook Graph API
{
"data": [
{
"birthday": "01/01/2000",
"first_name": "John",
"last_name": "Doe",
"hometown": {
"name": "Tampa, Florida"
},
},
{
"birthday": "03/01/2000",
"first_name": "Jane",
"last_name": "Doe",
"hometown": {
"name": "Gainesville, Florida"
},
}
],
"paging": {
"next": "<theAPIURL>"
}
}
// This filename is passed into whichever method this is in!
ifstream fileInput(filename.c_str());
if(!fileInput.is_open()){
cout << "Whoops! Something went wrong. Please check your input." << endl;
}
else{
string inputStr((istreambuf_iterator<char>(fileInput)), istreambuf_iterator<char>());
json_value data = * json_parse(inputStr.c_str());
json_value *list = data.u.object.values[0].value;
const int length = list->u.array.length;
json_value **array = data.u.object.values[0].value->u.array.values;
Person parsePersons[length];
int curIndex = 0;
for(int i = 0; i < length; i++){
for(int j = 0; j < array[i]->u.object.length; j++){
if (!strcmp(array[i]->u.object.values[j].name, "birthday")) {
cout << "Birthday: " << array[i]->u.object.values[j].value->u.string.ptr << endl;
}
else if(!strcmp(array[i]->u.object.values[j].name, "first_name") && array[i]->u.object.values[j].value->type != json_null){
cout << "First Name: " << array[i]->u.object.values[j].value->u.string.ptr << endl;
}
else if(!strcmp(array[i]->u.object.values[j].name, "last_name") && array[i]->u.object.values[j].value->type != json_null){
cout << "Last Name: " << array[i]->u.object.values[j].value->u.string.ptr << endl;
}
else if(!strcmp(array[i]->u.object.values[j].name, "hometown") && array[i]->u.object.values[j].value->type != json_null){
cout << "Hometown: " << array[i]->u.object.values[j].value->u.object.values[1].value->u.string.ptr << endl;
}
}
}
}
@jeanbza
Copy link

jeanbza commented Mar 9, 2015

Thank you!

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