json.cpp 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Maxwell Trussell <maxtrussell@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Assertions.h>
  8. #include <AK/JsonArray.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/JsonValue.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/StringView.h>
  13. #include <AK/Types.h>
  14. #include <AK/Vector.h>
  15. #include <LibCore/ArgsParser.h>
  16. #include <LibCore/File.h>
  17. #include <LibCore/System.h>
  18. #include <LibMain/Main.h>
  19. #include <unistd.h>
  20. static JsonValue query(JsonValue const& value, Vector<StringView>& key_parts, size_t key_index = 0);
  21. static void print(JsonValue const& value, int spaces_per_indent, int indent = 0, bool use_color = true);
  22. static void print_indent(int indent, int spaces_per_indent)
  23. {
  24. for (int i = 0; i < indent * spaces_per_indent; ++i)
  25. out(" ");
  26. }
  27. ErrorOr<int> serenity_main(Main::Arguments arguments)
  28. {
  29. TRY(Core::System::pledge("stdio rpath"));
  30. StringView path;
  31. StringView dotted_key;
  32. int spaces_in_indent = 4;
  33. Core::ArgsParser args_parser;
  34. args_parser.set_general_help("Pretty-print a JSON file with syntax-coloring and indentation.");
  35. args_parser.add_option(dotted_key, "Dotted query key", "query", 'q', "foo.*.bar");
  36. args_parser.add_option(spaces_in_indent, "Indent size", "indent-size", 'i', "spaces_in_indent");
  37. args_parser.add_positional_argument(path, "Path to JSON file", "path", Core::ArgsParser::Required::No);
  38. VERIFY(spaces_in_indent >= 0);
  39. args_parser.parse(arguments);
  40. RefPtr<Core::File> file;
  41. if (path == nullptr)
  42. file = Core::File::standard_input();
  43. else
  44. file = TRY(Core::File::open(path, Core::OpenMode::ReadOnly));
  45. TRY(Core::System::pledge("stdio"));
  46. auto file_contents = file->read_all();
  47. auto json = TRY(JsonValue::from_string(file_contents));
  48. if (!dotted_key.is_empty()) {
  49. auto key_parts = dotted_key.split_view('.');
  50. json = query(json, key_parts);
  51. }
  52. print(json, spaces_in_indent, 0, isatty(STDOUT_FILENO));
  53. outln();
  54. return 0;
  55. }
  56. void print(JsonValue const& value, int spaces_per_indent, int indent, bool use_color)
  57. {
  58. if (value.is_object()) {
  59. size_t printed_members = 0;
  60. auto& object = value.as_object();
  61. outln("{{");
  62. object.for_each_member([&](auto& member_name, auto& member_value) {
  63. ++printed_members;
  64. print_indent(indent + 1, spaces_per_indent);
  65. if (use_color)
  66. out("\"\033[33;1m{}\033[0m\": ", member_name);
  67. else
  68. out("\"{}\": ", member_name);
  69. print(member_value, spaces_per_indent, indent + 1, use_color);
  70. if (printed_members < static_cast<size_t>(object.size()))
  71. out(",");
  72. outln();
  73. });
  74. print_indent(indent, spaces_per_indent);
  75. out("}}");
  76. return;
  77. }
  78. if (value.is_array()) {
  79. size_t printed_entries = 0;
  80. auto array = value.as_array();
  81. outln("[");
  82. array.for_each([&](auto& entry_value) {
  83. ++printed_entries;
  84. print_indent(indent + 1, spaces_per_indent);
  85. print(entry_value, spaces_per_indent, indent + 1, use_color);
  86. if (printed_entries < static_cast<size_t>(array.size()))
  87. out(",");
  88. outln();
  89. });
  90. print_indent(indent, spaces_per_indent);
  91. out("]");
  92. return;
  93. }
  94. if (use_color) {
  95. if (value.is_string())
  96. out("\033[31;1m");
  97. else if (value.is_number())
  98. out("\033[35;1m");
  99. else if (value.is_bool())
  100. out("\033[32;1m");
  101. else if (value.is_null())
  102. out("\033[34;1m");
  103. }
  104. if (value.is_string())
  105. out("\"");
  106. out("{}", value.to_string());
  107. if (value.is_string())
  108. out("\"");
  109. if (use_color)
  110. out("\033[0m");
  111. }
  112. JsonValue query(JsonValue const& value, Vector<StringView>& key_parts, size_t key_index)
  113. {
  114. if (key_index == key_parts.size())
  115. return value;
  116. auto key = key_parts[key_index++];
  117. if (key == "*"sv) {
  118. Vector<JsonValue> matches;
  119. if (value.is_object()) {
  120. value.as_object().for_each_member([&](auto&, auto& member_value) {
  121. matches.append(query(member_value, key_parts, key_index));
  122. });
  123. } else if (value.is_array()) {
  124. value.as_array().for_each([&](auto& member) {
  125. matches.append(query(member, key_parts, key_index));
  126. });
  127. }
  128. return JsonValue(JsonArray(matches));
  129. }
  130. JsonValue result {};
  131. if (value.is_object()) {
  132. result = value.as_object().get(key);
  133. } else if (value.is_array()) {
  134. auto key_as_index = key.to_int();
  135. if (key_as_index.has_value())
  136. result = value.as_array().at(key_as_index.value());
  137. }
  138. return query(result, key_parts, key_index);
  139. }