Browse Source

Util: Add JSON accessors

master
Riyyi 2 years ago
parent
commit
c385432bb0
  1. 2
      src/util/json/array.h
  2. 4
      src/util/json/parser.cpp
  3. 2
      src/util/json/parser.h
  4. 13
      src/util/json/value.cpp
  5. 4
      src/util/json/value.h

2
src/util/json/array.h

@ -29,6 +29,8 @@ public:
m_values.emplace_back(std::move(value)); m_values.emplace_back(std::move(value));
} }
const std::vector<Value>& values() const { return m_values; }
private: private:
std::vector<Value> m_values; std::vector<Value> m_values;
}; };

4
src/util/json/parser.cpp

@ -28,7 +28,7 @@ Parser::~Parser()
// ----------------------------------------- // -----------------------------------------
void Parser::parse() Value Parser::parse()
{ {
Lexer lexer(m_input); Lexer lexer(m_input);
lexer.analyze(); lexer.analyze();
@ -81,6 +81,8 @@ void Parser::parse()
break; break;
} }
return result;
} }
// ----------------------------------------- // -----------------------------------------

2
src/util/json/parser.h

@ -24,7 +24,7 @@ public:
Parser(const std::string& input); Parser(const std::string& input);
virtual ~Parser(); virtual ~Parser();
void parse(); Value parse();
private: private:
Token peek(); Token peek();

13
src/util/json/value.cpp

@ -4,6 +4,7 @@
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
*/ */
#include <cassert> // assert
#include <string> #include <string>
#include <utility> // move #include <utility> // move
@ -64,6 +65,18 @@ Value::Value(const Object& value)
m_value.asObject = new Object(value); m_value.asObject = new Object(value);
} }
Value Value::operator[](size_t index)
{
assert(m_type == Type::Array);
return m_value.asArray->values().at(index);
}
Value Value::operator[](const std::string& key)
{
assert(m_type == Type::Object);
return m_value.asObject->members().at(key);
}
// ------------------------------------------ // ------------------------------------------
void Value::clear() void Value::clear()

4
src/util/json/value.h

@ -40,6 +40,10 @@ public:
Value(const Array& value); Value(const Array& value);
Value(const Object& value); Value(const Object& value);
// Array index operator
Value operator[](size_t index);
Value operator[](const std::string& key);
bool asBool() const { return m_value.asBool; } bool asBool() const { return m_value.asBool; }
double asDouble() const { return m_value.asDouble; } double asDouble() const { return m_value.asDouble; }
const std::string& asString() const { return *m_value.asString; } const std::string& asString() const { return *m_value.asString; }

Loading…
Cancel
Save