CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Common/Data/Format/JSONReader.h
Views: 1401
#pragma once12#include <cstring>3#include <string>4#include <vector>56#include "ext/gason/gason.h"7#include "Common/Common.h"89namespace json {1011struct JsonGet {12JsonGet(const JsonValue &value) : value_(value) {}1314int numChildren() const;15const JsonNode *get(const char *child_name) const;16const JsonNode *get(const char *child_name, JsonTag type) const;17const JsonNode *getArray(const char *child_name) const {18return get(child_name, JSON_ARRAY);19}20const JsonGet getDict(const char *child_name) const {21return JsonGet(get(child_name, JSON_OBJECT)->value);22}23const char *getStringOrNull(const char *child_name) const;24const char *getStringOr(const char *child_name, const char *default_value) const;25bool getString(const char *child_name, std::string *output) const;26bool getStringVector(std::vector<std::string> *vec) const;27double getFloat(const char *child_name) const;28double getFloat(const char *child_name, double default_value) const;29int getInt(const char *child_name) const;30int getInt(const char *child_name, int default_value) const;31bool getBool(const char *child_name) const;32bool getBool(const char *child_name, bool default_value) const;3334bool hasChild(const char *child_name, JsonTag child_type) const {35return get(child_name, child_type) != nullptr;36}3738operator bool() const {39return value_.getTag() != JSON_NULL;40}4142JsonValue value_;43};4445// Easy-wrapper46class JsonReader {47public:48JsonReader(const std::string &filename);49// Makes a copy, after this returns you can free the input buffer. Zero termination is not necessary.50JsonReader(const char *data, size_t size) {51buffer_ = (char *)malloc(size + 1);52if (buffer_) {53memcpy(buffer_, data, size);54buffer_[size] = 0;55parse();56}57}58JsonReader(const JsonNode *node) {59ok_ = true;60}6162~JsonReader() {63free(buffer_);64}6566bool ok() const { return ok_; }6768JsonGet root() { return root_.getTag() == JSON_OBJECT ? JsonGet(root_) : JsonGet(JSON_NULL); }69const JsonValue rootArray() const { return root_.getTag() == JSON_ARRAY ? root_ : JSON_NULL; }7071const JsonValue rootValue() const { return root_; }7273private:74bool parse();7576char *buffer_ = nullptr;77JsonAllocator alloc_;78JsonValue root_;79bool ok_ = false;8081DISALLOW_COPY_AND_ASSIGN(JsonReader);82};8384} // namespace json858687