0

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!

2

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I tried out this code and kept getting an error but I realized I had to add the json file to my working directory. After doing that, it did exactly what I wanted to. Where was this code found? I don't see it in the parser's readme. (Now I'm trying to figure out something like "if assignmentName is Research Paper, then print dueDate")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.