简体   繁体   中英

`JSONcpp` C++ library to modify JSON files

I was looking for JSON C++ libraries and the JSONcpp library seems the most used.

I would like to use for the following problem. Basically suppose I have a JSON file like:

{"data" : [
  {"id": 1, "val" : [
      {"id":"el1", "x": val1, "y" : val2}, 
      {"id":"el2", "x": val3, "y" : val4}
      ],
  {"id": 2, "val" : [
        {"id":"el1", "x": val5, "y" : val6},
        {"id":"el2", "x": val5, "y" : val8},
        {"id":"el3", "x": val7, "y" : val10}
  ]
  {"id": 3, "val" : [
        {"id":"el1", "x": val1, "y" : val2},
        {"id":"el2", "x": val1, "y" : val2},
        {"id":"el3", "x": val1, "y" : val2},
        {"id":"el4", "x": val1, "y" : val2},
        {"id":"el5", "x": val1, "y" : val2}
  ]
  ....
}

The first run of the interactive C++ program generate the file. Next times the program is run at first it loads the JSON values. The list represented by the outer array can be modified by adding an element, removing an element or modifying one and the same for the inner elements.

At each run I want to modify the file. Appending an element to the file should be simple. But does the library allow to modify only one single element of the array (so only some lines of the file)? Or each time the file should be/is deleted and created anew?

Modifying files is not really a concept that exists in the main.

Operating systems don't let you "add data" and "remove data" from arbitrary points in a file — you can only make a file longer/shorter and overwrite stuff inside it.

Therefore, when you think you're doing complex modifications in a text editor, it's doing some fancy stuff for you.

C++ is not immune to this. Its file streams permit you to put the cursor at a point in the file, and start writing data. This will overwrite whatever's behind the cursor.

As a consequence, we tend to just load the data, modify it in memory, then create a new file (possibly entirely overwriting the old one), and libraries like JsonCpp follow that too.

When your file is very large then yes you need more complex ways to manage data, and that's where memory mapping may be useful. But ultimately this will have more to do with how you safely treat a memory mapped file as a string in C++, than about how to deal specifically with JSON or JsonCpp.

If your file is "very very long" such that recreating the file is not feasible, it's probably also too long to be managing completely in memory, and probably also too long for JSON to be appropriate, and so you should consider some other storage mechanism, like a database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM