1

I use jsoncpp to parse my config.json. It library use std::map to contain pairs key:value. Map is unordered container. Now I need to parse elements in the same order in which they are in the file (do not ask why, it's not my whimsy).

I did some searching and I found that

you can write your own parser or rewrite jsoncpp to use list instead of map.

Can I really replace the list with a map in jsoncpp?

Or, maybe, you give me some idea, how I can save order of elements when I parse file with jsoncpp?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
murzagurskiy
  • 1,273
  • 1
  • 20
  • 44
  • 1
    This information doesn't help you with your problem, but [`std::map`](http://en.cppreference.com/w/cpp/container/map) is definitely an ordered container, however it might not be ordered the way you like it. – Some programmer dude Sep 08 '15 at 13:54
  • 1
    You could use json-spirit to parse it, I think it's configurable what datatypes it uses? FWIW you might have a hard time with this because I think JSON is specified such that there is no logical order to the key:value pairs. If you really need to have it in a list or a vector, you might be best off just... taking the pairs out of the map and putting them in a list or vector. – Chris Beck Sep 08 '15 at 13:55
  • Re *do not ask why, it's not my whimsy* -- If it's someone else's whimsy, tell that person that they are using JSON incorrectly. A JSON object has no order (which means any order used by an implementation is okay). If you wanted something in which order matters, use a JSON array. It's the duty of a responsible programmer to push back on bad requirements. – David Hammen Sep 08 '15 at 17:13
  • 1
    Cou certainly *can* replace `std::map` with `std::list`, but most probably you'd have to also modify `Json::Value::operator[]` to perform linear search instead of map lookup, at least. – el.pescado - нет войне Sep 09 '15 at 06:28

2 Answers2

0
std::ifstream i("input.json");
auto j = nlohmann::ordered_json::parse(i);
std::cout << j.dump(2) << std::endl;
Qiuren
  • 19
  • 3
-1

I think you need to use another container rather than QMap in jsoncpp that maintain insertion order of values

unfortunately Qt doesn't have such a data type and you have to do it on your own because neither QMap nor QHash maintains insertion order

if you can use Boost it has a unordered_map http://www.boost.org/doc/libs/1%5F37%5F0/doc/html/unordered.html1

See:

QMap but without sorting by key 1

Make Map Key Sorted According To Insert Sequence1

A std::map that keep track of the order of insertion?1

Community
  • 1
  • 1
Yasser Sobhy
  • 145
  • 3
  • 14