capitalize.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // JSON condenser example
  2. // This example parses JSON from stdin with validation,
  3. // and re-output the JSON content to stdout with all string capitalized, and without whitespace.
  4. #include <rtthread.h>
  5. #include "rapidjson/reader.h"
  6. #include "rapidjson/writer.h"
  7. #include "rapidjson/filereadstream.h"
  8. #include "rapidjson/filewritestream.h"
  9. #include "rapidjson/error/en.h"
  10. #include <vector>
  11. #include <cctype>
  12. using namespace rapidjson;
  13. template<typename OutputHandler>
  14. struct CapitalizeFilter {
  15. CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
  16. bool Null() { return out_.Null(); }
  17. bool Bool(bool b) { return out_.Bool(b); }
  18. bool Int(int i) { return out_.Int(i); }
  19. bool Uint(unsigned u) { return out_.Uint(u); }
  20. bool Int64(int64_t i) { return out_.Int64(i); }
  21. bool Uint64(uint64_t u) { return out_.Uint64(u); }
  22. bool Double(double d) { return out_.Double(d); }
  23. bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); }
  24. bool String(const char* str, SizeType length, bool) {
  25. buffer_.clear();
  26. for (SizeType i = 0; i < length; i++)
  27. buffer_.push_back(static_cast<char>(std::toupper(str[i])));
  28. return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
  29. }
  30. bool StartObject() { return out_.StartObject(); }
  31. bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
  32. bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
  33. bool StartArray() { return out_.StartArray(); }
  34. bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
  35. OutputHandler& out_;
  36. std::vector<char> buffer_;
  37. private:
  38. CapitalizeFilter(const CapitalizeFilter&);
  39. CapitalizeFilter& operator=(const CapitalizeFilter&);
  40. };
  41. int capitalize(int, char*[]) {
  42. // Prepare JSON reader and input stream.
  43. Reader reader;
  44. char readBuffer[1024];
  45. FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
  46. // Prepare JSON writer and output stream.
  47. char writeBuffer[1024];
  48. FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
  49. Writer<FileWriteStream> writer(os);
  50. // JSON reader parse from the input stream and let writer generate the output.
  51. CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
  52. if (!reader.Parse(is, filter)) {
  53. fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
  54. return 1;
  55. }
  56. return 0;
  57. }
  58. MSH_CMD_EXPORT(capitalize, rapid json capitalize example);