4 ms·
I would love you to show us the C++ equivalent of this trivial PHP code: <?php $data = json_decode(file_get_contents('data.json')); foreach ($data
by imaginenore 11y ago
I would love you to show us the C++ equivalent of this trivial PHP code:
<?php
$data = json_decode(file_get_contents('data.json'));
foreach ($data as $obj) {
echo $obj->x . ',' . $obj->y . "\n";
}
That's the entire script.
- matt_d 11y agoTake a look at JSON for Modern C++: https://github.com/nlohmann/json https://github.com/nlohmann/json Perhaps this example (benchmark, actually) is close enough: https://github.com/nlohmann/json/blob/master/benchmarks/benchmarks.cpp#L47 https://github.com/nlohmann/json/blob/master/benchmarks/benc... Note that the above also performs mini-benchmark with multiple iterations, dumping parsed data to another file, and finishes with a clean-up of the aforementioned dump target file. The core (read, parse, write) can be simplified to: std::ifstream input_file("data.json"); nlohmann::json data; data << input_file; std::cout << data;
- imaginenore 11y agoNo no no, this won't compile. Write the complete code, with all the includes, main function, etc. And write it correctly, iterating over the data, accessing the object fields.
- nmjohn 11y agoThere is _absolutley_ no value for a language to provide handy built-in functions that are trivially made available by a library. If we were talking about language constructs/semantics or flow-control abilities, I'd have a very different opinion - but not having a json decoder builtin, is no reason to use or not use a language.
- imaginenore 11y agoDon't dodge the question. Use any available library you want, just type the code that will compile.
- matt_d 11y agoAll right, then: This one is complete (compiles, runs, iterates through the data, accessing only fields "x" and "y"): #include <fstream> #include <json.hpp> int main() { std::ifstream input_file("data.json"); nlohmann::json data; data << input_file; for (auto obj : data) std::cout << obj["x"] << ',' << obj["y"] << '\n'; }