convert_json.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include <vector>
  17. #include <iostream>
  18. #include <sstream>
  19. #include "convert_json.h"
  20. #include "content/mods.h"
  21. #include "config.h"
  22. #include "log.h"
  23. #include "settings.h"
  24. #include "httpfetch.h"
  25. #include "porting.h"
  26. Json::Value fetchJsonValue(const std::string &url,
  27. std::vector<std::string> *extra_headers)
  28. {
  29. HTTPFetchRequest fetch_request;
  30. HTTPFetchResult fetch_result;
  31. fetch_request.url = url;
  32. fetch_request.caller = HTTPFETCH_SYNC;
  33. if (extra_headers != NULL)
  34. fetch_request.extra_headers = *extra_headers;
  35. httpfetch_sync(fetch_request, fetch_result);
  36. if (!fetch_result.succeeded) {
  37. return Json::Value();
  38. }
  39. Json::Value root;
  40. std::istringstream stream(fetch_result.data);
  41. Json::CharReaderBuilder builder;
  42. builder.settings_["collectComments"] = false;
  43. std::string errs;
  44. if (!Json::parseFromStream(builder, stream, &root, &errs)) {
  45. errorstream << "URL: " << url << std::endl;
  46. errorstream << "Failed to parse json data " << errs << std::endl;
  47. if (fetch_result.data.size() > 100) {
  48. errorstream << "Data (" << fetch_result.data.size()
  49. << " bytes) printed to warningstream." << std::endl;
  50. warningstream << "data: \"" << fetch_result.data << "\"" << std::endl;
  51. } else {
  52. errorstream << "data: \"" << fetch_result.data << "\"" << std::endl;
  53. }
  54. return Json::Value();
  55. }
  56. return root;
  57. }
  58. std::string fastWriteJson(const Json::Value &value)
  59. {
  60. std::ostringstream oss;
  61. Json::StreamWriterBuilder builder;
  62. builder["indentation"] = "";
  63. std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
  64. writer->write(value, &oss);
  65. return oss.str();
  66. }