JsonPath.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/JsonObject.h>
  7. #include <AK/JsonPath.h>
  8. #include <AK/JsonValue.h>
  9. namespace AK {
  10. JsonPathElement JsonPathElement::any_array_element { Kind::AnyIndex };
  11. JsonPathElement JsonPathElement::any_object_element { Kind::AnyKey };
  12. JsonValue JsonPath::resolve(const JsonValue& top_root) const
  13. {
  14. auto root = top_root;
  15. for (auto const& element : *this) {
  16. switch (element.kind()) {
  17. case JsonPathElement::Kind::Key:
  18. root = JsonValue { root.as_object().get(element.key()) };
  19. break;
  20. case JsonPathElement::Kind::Index:
  21. root = JsonValue { root.as_array().at(element.index()) };
  22. break;
  23. default:
  24. VERIFY_NOT_REACHED();
  25. }
  26. }
  27. return root;
  28. }
  29. String JsonPath::to_string() const
  30. {
  31. StringBuilder builder;
  32. builder.append("{ .");
  33. for (auto const& el : *this) {
  34. builder.append(" > ");
  35. builder.append(el.to_string());
  36. }
  37. builder.append(" }");
  38. return builder.to_string();
  39. }
  40. }