Browse Source

Util: Add parse() and dump() to Json::Value

master
Riyyi 2 years ago
parent
commit
9f7fe81ef6
  1. 46
      src/util/json/value.cpp
  2. 14
      src/util/json/value.h

46
src/util/json/value.cpp

@ -4,12 +4,15 @@
* SPDX-License-Identifier: MIT
*/
#include <cassert> // assert
#include <cassert> // assert
#include <cstdint> // uint32_t
#include <iostream>
#include <string>
#include <utility> // move
#include "util/json/array.h"
#include "util/json/object.h"
#include "util/json/stringify.h"
#include "util/json/value.h"
namespace Json {
@ -66,6 +69,24 @@ Value::Value(const Object& value)
}
Value Value::operator[](size_t index)
// ------------------------------------------
Value Value::parse(const std::string& input)
{
Parser parser(input);
Value value;
value = parser.parse();
return value;
}
std::string Value::dump(const uint32_t indent, const char indentCharacter) const
{
Stringify stringify(*this, indent, indentCharacter);
return stringify.dump();
}
{
assert(m_type == Type::Array);
return m_value.asArray->values().at(index);
@ -117,4 +138,27 @@ void Value::copyFrom(const Value& other)
}
}
// ------------------------------------------
std::istream& operator>>(std::istream& input, Value& value)
{
std::string inputString;
char buffer[4096];
while (input.read(buffer, sizeof(buffer))) {
inputString.append(buffer, sizeof(buffer));
}
inputString.append(buffer, input.gcount());
Parser parser(inputString);
value = parser.parse();
return input;
}
std::ostream& operator<<(std::ostream& output, const Value& value)
{
return output << value.dump(4);
}
} // namespace Json

14
src/util/json/value.h

@ -7,6 +7,8 @@
#ifndef JSON_VALUE_H
#define JSON_VALUE_H
#include <cstdint> // uint32_t
#include <iostream> // istream, ostream
#include <string>
namespace Json {
@ -25,7 +27,7 @@ public:
Object, // {}
};
Value() {}
Value(std::nullptr_t = nullptr) {}
virtual ~Value() { clear(); }
// Copy constructor
@ -40,6 +42,11 @@ public:
Value(const Array& value);
Value(const Object& value);
// ------------------------------------------
static Value parse(const std::string& input);
std::string dump(const uint32_t indent = 0, const char indentCharacter = ' ') const;
// Array index operator
Value operator[](size_t index);
Value operator[](const std::string& key);
@ -64,9 +71,12 @@ private:
std::string* asString;
Array* asArray;
Object* asObject;
} m_value;
} m_value {};
};
std::istream& operator>>(std::istream& input, Value& value);
std::ostream& operator<<(std::ostream& output, const Value& value);
} // namespace Json
#endif // JSON_VALUE_H

Loading…
Cancel
Save