Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parsing from stream leads to an array #589

Closed
matsbror opened this issue May 19, 2017 · 6 comments
Closed

Parsing from stream leads to an array #589

matsbror opened this issue May 19, 2017 · 6 comments

Comments

@matsbror
Copy link

matsbror commented May 19, 2017

Hello,

I parse the following file from a stream:

{
  "anInt": 500,
  "aString": "fixed"
}

Then I send it to an output stream with dump(4), which yields the following output:

[
    {
        "aString": "fixed",
        "anInt": 500
    }
]

It has become embedded in an array. Do you know why and how can I get around it?
If it is consistent, I can of course deal with it as it is.

@nlohmann
Copy link
Owner

This is odd. Can you please provide the code that you execute for this?

@matsbror
Copy link
Author

#include <iostream>
#include <fstream>
#include <cstdio>

#include "json.hpp"

using json = nlohmann::json;

json readJsonFile(const std::string & fileName){
    std::ifstream jsonFile(fileName);
    return json::parse(jsonFile);
}
int main() {
    json bidConfig { readJsonFile("../test.json") };
    std::cout << bidConfig.dump(4) << std::endl;
    return 0;
}

`

@matsbror
Copy link
Author

edit the file name to where you have your json

@matsbror matsbror reopened this May 19, 2017
@matsbror
Copy link
Author

matsbror commented May 19, 2017

It seems to be related to that I pass the json document as return value from the readJsonFile function. If I parse it and use it in the same function, there is no array.

I can also pass the document as reference to the function that reads it and return it that way. It seems as it is the return value that is not working and it is not related to parsing.

@matsbror
Copy link
Author

OK, it is related to the universal initalization. It takes it as an initializer list and thus makes an array out of it. If I change:

json bidConfig { readJsonFile("../test.json") };

to

json bidConfig = readJsonFile("../test.json");

it works as expected.

@nlohmann
Copy link
Owner

Yes, that is it. We use the braces as array literals, e.g. {1,2,3}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants