Skip to content

How to handle json files? #333

Closed
Closed

Description

@himanshub16

I tried handling files, but it lead to runtime errors. Could you please help me figure out the bug?

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

using json = nlohmann::json;
using namespace std;
int main()
{
ifstream file ("data.json", ios::in | ios::ate);
if (!file.is_open()) return 1;

streampos size = file.tellg();
file.seekg(0, ios::beg);
char *memblock = new char[size];
file.read(memblock, size);
file.close();

json data = json::parse(memblock);

// another approach
string s = memblock;
json data = json::parse(s);
// or
json data = json::parse(s.c_str());
...

All three methods to initialize json give runtime error :
terminate called after throwing an instance of 'std::invalid_argument' what(): parse error - unexpected number literal; expected string literal [1] 8754 abort (core dumped) ./a.out

The json file is
{ 1 : { "name": "himanshu" }, 2 : { "name":"shekhar" } }

Activity

  1. himanshub16 commented on Oct 15, 2016

    @himanshub16
    Author

    Got it. My JSON files are syntactically wrong.
    It should be :
    { "1" : { .. } , "2" : { ... } }

    They should be strings. 😞

    Sorry to bother you guys.

  2. added
    solution: invalid
    on Oct 15, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: questionsolution: invalid

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions