C++中如何访问JSON文件的特定字段(如_id和duration)
Hey there! Right now your code is just reading the JSON file as raw text and printing it out—totally fine for seeing the whole thing, but to grab specific fields like _id and duration, you'll need a proper JSON parsing library instead of manually reading characters. Writing your own JSON parser is error-prone (think about nested objects, escaped characters, different data types) and unnecessary when there are great, lightweight options out there.
Recommended Library: nlohmann/json
This is my go-to for most JSON parsing tasks in C++ because it's header-only (no linking required), super intuitive, and works with modern C++ standards. Here's how to use it to solve your problem:
Step 1: Get the Library
- Download the single
json.hppfile from its official source, or use a package manager like vcpkg, Conan, or your distro's package manager if you prefer. - Drop it into your project directory, or ensure your compiler can find it in your include path.
Step 2: Updated Code to Extract Fields
Replace your existing code with this, which parses the JSON and extracts the fields you need:
#include <iostream> #include <fstream> #include <nlohmann/json.hpp> // Define an alias to make code cleaner using json = nlohmann::json; int main() { std::ifstream people_file("query.json"); // First, check if the file opened successfully if (!people_file.is_open()) { std::cerr << "Oops! Failed to open query.json" << std::endl; return 1; } // Parse the entire JSON file into a json object json json_data; people_file >> json_data; // Handle two common JSON structures: single object or array of objects if (json_data.is_object()) { // Check if both fields exist before accessing them (avoids crashes) if (json_data.contains("_id") && json_data.contains("duration")) { std::string id = json_data["_id"]; // Use int if duration is an integer, double if it's a float int duration = json_data["duration"]; std::cout << "Extracted _id: " << id << std::endl; std::cout << "Extracted duration: " << duration << std::endl; } else { std::cerr << "JSON object is missing _id or duration field!" << std::endl; } } else if (json_data.is_array()) { // Loop through each item in the array for (const auto& item : json_data) { if (item.contains("_id") && item.contains("duration")) { std::string id = item["_id"]; auto duration = item["duration"]; // Auto-detects type (int/double) std::cout << "Item - _id: " << id << ", duration: " << duration << std::endl; } else { std::cerr << "Skipping an item: missing required fields" << std::endl; } } } else { std::cerr << "JSON data is neither an object nor an array—unexpected format!" << std::endl; } return 0; }
Key Notes:
- Field Existence Check: Always use
contains()to verify the fields exist before accessing them. This prevents undefined behavior if the JSON is missing the fields you expect. - Type Handling: The library automatically converts JSON values to C++ types (e.g., JSON string →
std::string, JSON number →int/double). Adjust the type ofdurationbased on your actual JSON data (if it's a float, usedoubleinstead ofint). - Error Handling: Added checks for file opening and JSON structure to make the code more robust.
Alternative: RapidJSON
If you need extreme performance (e.g., parsing huge JSON files), RapidJSON is a great choice. It's faster but has a more verbose API. The core idea is similar though—parse the JSON into a DOM (Document Object Model) and then traverse it to access your fields.
内容的提问来源于stack exchange,提问作者Lieutenant. X

