Last active
March 2, 2020 00:38
-
-
Save rubenwardy/b83ec54ea36edbb0bc9755c002056ad2 to your computer and use it in GitHub Desktop.
Sol3 Read/parse JSON from file or string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <json/json.h> | |
#include <fstream> | |
#include <sstream> | |
namespace { | |
sol::object json_to_lua(Json::Value value, sol::this_state state) { | |
switch (value.type()) { | |
case Json::nullValue: | |
return sol::nil; | |
case Json::intValue: | |
case Json::uintValue: | |
return sol::make_object(state.L, value.asInt()); | |
case Json::realValue: | |
return sol::make_object(state.L, value.asDouble()); | |
case Json::stringValue: | |
return sol::make_object(state.L, value.asString()); | |
case Json::booleanValue: | |
return sol::make_object(state.L, value.asBool()); | |
case Json::arrayValue: | |
case Json::objectValue: { | |
sol::table table(state.L, sol::create); | |
for (Json::Value::const_iterator itr = value.begin(); | |
itr != value.end(); itr++) { | |
if (itr.key().isInt()) { | |
table[itr.key().asInt() + 1] = json_to_lua(*itr, state); | |
} else { | |
table[json_to_lua(itr.key(), state)] = json_to_lua(*itr, state); | |
} | |
} | |
return table; | |
} | |
} | |
assert(false); | |
} | |
} // namespace | |
sol::object scripting::l_parse_json( | |
const std::string &value, sol::this_state state) { | |
Json::Value root; | |
std::string errors; | |
auto reader = Json::CharReaderBuilder().newCharReader(); | |
bool success = reader->parse( | |
value.c_str(), | |
value.c_str() + value.size(), | |
&root, | |
&errors); | |
delete reader; | |
if (!success) { | |
return sol::nil; | |
} | |
return json_to_lua(root, state); | |
} | |
sol::object scripting::l_read_json( | |
const std::string &path, sol::this_state state) { | |
Json::Value root; | |
{ | |
std::ifstream is(path); | |
is >> root; | |
} | |
return json_to_lua(root, state); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment