json.cpp 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. auto file = TRY(Core::File::open_file_or_standard_stream(path, Core::File::OpenMode::Read));
  41. TRY(Core::System::pledge("stdio"));
  42. auto file_contents = TRY(file->read_until_eof());
  43. auto json = TRY(JsonValue::from_string(file_contents));
  44. if (!dotted_key.is_empty()) {
  45. auto key_parts = dotted_key.split_view('.');
  46. json = query(json, key_parts);
  47. }
  48. print(json, spaces_in_indent, 0, isatty(STDOUT_FILENO));
  49. outln();
  50. return 0;
  51. }
  52. void print(JsonValue const& value, int spaces_per_indent, int indent, bool use_color)
  53. {
  54. if (value.is_object()) {
  55. size_t printed_members = 0;
  56. auto& object = value.as_object();
  57. outln("{{");
  58. object.for_each_member([&](auto& member_name, auto& member_value) {
  59. ++printed_members;
  60. print_indent(indent + 1, spaces_per_indent);
  61. if (use_color)
  62. out("\"\033[33;1m{}\033[0m\": ", member_name);
  63. else
  64. out("\"{}\": ", member_name);
  65. print(member_value, spaces_per_indent, indent + 1, use_color);
  66. if (printed_members < static_cast<size_t>(object.size()))
  67. out(",");
  68. outln();
  69. });
  70. print_indent(indent, spaces_per_indent);
  71. out("}}");
  72. return;
  73. }
  74. if (value.is_array()) {
  75. size_t printed_entries = 0;
  76. auto array = value.as_array();
  77. outln("[");
  78. array.for_each([&](auto& entry_value) {
  79. ++printed_entries;
  80. print_indent(indent + 1, spaces_per_indent);
  81. print(entry_value, spaces_per_indent, indent + 1, use_color);
  82. if (printed_entries < static_cast<size_t>(array.size()))
  83. out(",");
  84. outln();
  85. });
  86. print_indent(indent, spaces_per_indent);
  87. out("]");
  88. return;
  89. }
  90. if (use_color) {
  91. if (value.is_string())
  92. out("\033[31;1m");
  93. else if (value.is_number())
  94. out("\033[35;1m");
  95. else if (value.is_bool())
  96. out("\033[32;1m");
  97. else if (value.is_null())
  98. out("\033[34;1m");
  99. }
  100. out("{}", value);
  101. if (use_color)
  102. out("\033[0m");
  103. }
  104. JsonValue query(JsonValue const& value, Vector<StringView>& key_parts, size_t key_index)
  105. {
  106. if (key_index == key_parts.size())
  107. return value;
  108. auto key = key_parts[key_index++];
  109. if (key == "*"sv) {
  110. Vector<JsonValue> matches;
  111. if (value.is_object()) {
  112. value.as_object().for_each_member([&](auto&, auto& member_value) {
  113. matches.append(query(member_value, key_parts, key_index));
  114. });
  115. } else if (value.is_array()) {
  116. value.as_array().for_each([&](auto& member) {
  117. matches.append(query(member, key_parts, key_index));
  118. });
  119. }
  120. return JsonValue(JsonArray(matches));
  121. }
  122. JsonValue result {};
  123. if (value.is_object()) {
  124. result = value.as_object().get(key).value_or({});
  125. } else if (value.is_array()) {
  126. auto key_as_index = key.to_number<int>();
  127. if (key_as_index.has_value())
  128. result = value.as_array().at(key_as_index.value());
  129. }
  130. return query(result, key_parts, key_index);
  131. }