Skip to content

Keys when iterating over objects #67

Closed
@mlund

Description

I'm trying to iterate over a json input file containing an unknown number of molecules (see below). For each of these the key is the name which I currently have found no way to extract. Is this possible?

Code:

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

/*
 * minimal.json:
 * {
 *   "moleculelist" : { 
 *     "salt" : { "atoms":"Na Cl", "atomic":true, "Ninit":1 },
 *     "water" : { "atoms":"H H O", "atomic":false, "Ninit":55 }
 *   }
 * }
 */

using json = nlohmann::json;

int main() {
  std::ifstream f("minimal.json");
  if (f) {
    json j;
    j << f;
    if ( ! j["moleculelist"].empty() )
      for ( auto &mol : j["moleculelist"] )
        if ( mol.is_object() ) {
          // how to get entry keys? (i.e. "salt", "water", etc.)
          for ( auto &i : mol )
            std::cout << i << "\n";
        }
  }
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions