Home > Back-end >  Converting json file to json object jumbles up the order of objects
Converting json file to json object jumbles up the order of objects

Time:10-12

I am trying to parse a json file into a json object using nlohmann json library.

This is the json file:

{
    "n":1,
    "data":
    {
        "name":"Chrome",
        "description":"Browse the internet.",
        "isEnabled":true
    }
}

This is my code:

#include <nlohmann/json.hpp>
#include <iostream>
#include <fstream>

using namespace std;
using json = nlohmann::json;

int main()
{
    ifstream f("/Users/callum/sfucourses/cmpt373/test/example2.json");
    json data = json::parse(f);
    cout << data << endl;
}

If I don't do the parse and just do cout << f.rdbuf() I get correct output:

./interpret
/Users/callum/sfucourses/cmpt373/build
{
    "n":1,
    "data":
    {
        "name":"Chrome",
        "description":"Browse the internet.",
        "isEnabled":true
    }
}

but if I do the parse and print out the json object 'data',then "n":1 and "name":"Chrome" is placed at the end instead of the beginning:

./interpret
{"data":{"description":"Browse the internet.","isEnabled":true,"name":"Chrome"},"n":1}

How do I get it to print in the correct order?

CodePudding user response:

JSON is normally not ordered, but the library provides nlohmann::ordered_json that keeps the insertion order:

auto data = nlohmann::ordered_json::parse(f);

Parsing the file like above and printing it like you do produces this output:

{"n":1,"data":{"name":"Chrome","description":"Browse the internet.","isEnabled":true}}
  • Related