JSON.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Value.h>
  8. #include <LibTextCodec/Decoder.h>
  9. #include <LibWeb/Infra/JSON.h>
  10. #include <LibWeb/WebIDL/ExceptionOr.h>
  11. namespace Web::Infra {
  12. // https://infra.spec.whatwg.org/#parse-a-json-string-to-a-javascript-value
  13. WebIDL::ExceptionOr<JS::Value> parse_json_string_to_javascript_value(JS::VM& vm, StringView string)
  14. {
  15. auto& realm = *vm.current_realm();
  16. // 1. Return ? Call(%JSON.parse%, undefined, « string »).
  17. return TRY(JS::call(vm, realm.intrinsics().json_parse_function(), JS::js_undefined(), JS::js_string(vm, string)));
  18. }
  19. // https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
  20. WebIDL::ExceptionOr<JS::Value> parse_json_bytes_to_javascript_value(JS::VM& vm, ReadonlyBytes bytes)
  21. {
  22. // 1. Let string be the result of running UTF-8 decode on bytes.
  23. TextCodec::UTF8Decoder decoder;
  24. auto string = decoder.to_utf8(bytes);
  25. // 2. Return the result of parsing a JSON string to an Infra value given string.
  26. return parse_json_string_to_javascript_value(vm, string);
  27. }
  28. // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
  29. WebIDL::ExceptionOr<String> serialize_javascript_value_to_json_string(JS::VM& vm, JS::Value value)
  30. {
  31. auto& realm = *vm.current_realm();
  32. // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
  33. auto result = TRY(JS::call(vm, realm.intrinsics().json_stringify_function(), JS::js_undefined(), value));
  34. // 2. If result is undefined, then throw a TypeError.
  35. if (result.is_undefined())
  36. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Result of stringifying value must not be undefined"sv };
  37. // 3. Assert: result is a string.
  38. VERIFY(result.is_string());
  39. // 4. Return result.
  40. return result.as_string().string();
  41. }
  42. // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-json-bytes
  43. WebIDL::ExceptionOr<ByteBuffer> serialize_javascript_value_to_json_bytes(JS::VM& vm, JS::Value value)
  44. {
  45. auto& realm = *vm.current_realm();
  46. // 1. Let string be the result of serializing a JavaScript value to a JSON string given value.
  47. auto string = TRY(serialize_javascript_value_to_json_string(vm, value));
  48. // 2. Return the result of running UTF-8 encode on string.
  49. // NOTE: LibJS strings are stored as UTF-8.
  50. return TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(string.bytes()));
  51. }
  52. }