m3lixir
m3lixir

Reputation: 65

Simple output from json file in C++?

I'm fairly new to C++ and am having trouble working with a json file. I am using Xcode (version 6.4). For example, my json file has a similar format to this:

[
 {
  "assignmentName": "Physics 1",
  "dueDate": "2015-10-15T20:11:20Z",
  "priority": "High",
 },
 {
  "assignmentName": "Research Paper",
  "dueDate": "2015-11-18T00:40:25Z",
  "priority": "Low"
 }
]

An example of what I am trying to do is write code that looks for information in my json file. If I wanted to print the name of an assignment that is due on November 11, 2015, I would want my output to be "Research Paper".

I've been working on this for the past few days and just keep getting stuck. I've checked out http://www.json.org and looked through the json parsers listed under C++. I've tried to work with them, but either (1) their code is too complicated for me to work with (I don't understand the syntax, even after reading their examples) or (2) I am asked to use other libraries. After looking at every parser underneath the C++ list, json (https://github.com/nlohmann/json) seems like the simplest parser for me to use, but I still feel very lost.

I'm looking for something simple. All I want to do is output the value of whatever variable I'm calling for in my json file (calling for "assignmentName", print "Physics 1")).

From speaking with a friend and vaguely trying to understand the parsers, it seems that in order for me to get the value of some variable in my json file, I need to actually paste the contents of my json file into my Xcode project. Is this true?

If anyone could direct me to a better parser, a better method, or some sort of syntax dictionary for these parsers, it would be highly appreciated!

Upvotes: 0

Views: 2599

Answers (1)

WorldSEnder
WorldSEnder

Reputation: 5044

With the json library you mentioned the relevant code should be

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

using json = nlohmann::json;
// ... In some method, e.g. main...
std::ifstream file = {"yourfilename.json"};
json obj;
file >> obj;
std::cout << obj[0]["dueDate"]; // Debug output
// End of code

Upvotes: 1

Related Questions