json_easy_parser.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/generic/vector.h>
  4. #include <util/stream/input.h>
  5. #include <util/stream/output.h>
  6. #include "json_easy_parser_impl.h"
  7. namespace NJson {
  8. /* This class filters out nodes from a source JSON by a xpath-style description. It represent these nodes as a tab-delimited string (or a vector).
  9. * It is useful if you need to parse a data which comes into JSON in a known and fixed format.
  10. * Fields are set as a list of keys separated by slash, for example:
  11. * Field x/y/z in JSON { "x" : { "y" : { "w" : 1, "z" : 2 } } contains number 2.
  12. * In a path to a field you can also provide a special array identifier "[]", identifier of a particular field in an array (for example "[4]") or wildcard "*".
  13. *
  14. * The parser of the class supports parsing of several fields. Each of them could be marked as mandatory or as optional.
  15. * If a mandatory field is not found in JSON, then Parse() returns false and ConvertToTabDelimited() returns an empty string.
  16. * If an optional field is not found in JSON, then it's value in Parse()/ConvertToTabDelimited() is an empty string.
  17. * In particular ConvertToTabDelimited() always returns either an empty string, or a string of the same number of tab-delimited fields starting from the same Prefix.
  18. *
  19. * NB! Library can not extract values of not a simple type (namely it doesn't support the case when a result is a vocabulary or an array) from JSON.
  20. * If you expect such a case, please check json_value.h.
  21. */
  22. class TJsonParser {
  23. TString Prefix;
  24. struct TField {
  25. TVector<TPathElem> Path;
  26. bool NonEmpty;
  27. };
  28. TVector<TField> Fields;
  29. friend class TRewriteJsonImpl;
  30. void ConvertToTabDelimited(IInputStream& in, IOutputStream& out) const;
  31. public:
  32. void SetPrefix(const TString& prefix) {
  33. Prefix = prefix;
  34. }
  35. void AddField(const TString& path, bool mustExist);
  36. TString ConvertToTabDelimited(const TString& json) const;
  37. bool Parse(const TString& json, TVector<TString>* res) const;
  38. };
  39. }