summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/Infra/JSON.cpp
blob: 3d39d719ce26762da3f62dec592634a1e1e2512e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Value.h>
#include <LibTextCodec/Decoder.h>
#include <LibWeb/Infra/JSON.h>
#include <LibWeb/WebIDL/ExceptionOr.h>

namespace Web::Infra {

// https://infra.spec.whatwg.org/#parse-a-json-string-to-a-javascript-value
WebIDL::ExceptionOr<JS::Value> parse_json_string_to_javascript_value(JS::VM& vm, StringView string)
{
    auto& realm = *vm.current_realm();

    // 1. Return ? Call(%JSON.parse%, undefined, « string »).
    return TRY(JS::call(vm, realm.intrinsics().json_parse_function(), JS::js_undefined(), JS::PrimitiveString::create(vm, string)));
}

// https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
WebIDL::ExceptionOr<JS::Value> parse_json_bytes_to_javascript_value(JS::VM& vm, ReadonlyBytes bytes)
{
    // 1. Let string be the result of running UTF-8 decode on bytes.
    TextCodec::UTF8Decoder decoder;
    auto string = decoder.to_utf8(bytes);

    // 2. Return the result of parsing a JSON string to an Infra value given string.
    return parse_json_string_to_javascript_value(vm, string);
}

// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
WebIDL::ExceptionOr<DeprecatedString> serialize_javascript_value_to_json_string(JS::VM& vm, JS::Value value)
{
    auto& realm = *vm.current_realm();

    // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
    auto result = TRY(JS::call(vm, realm.intrinsics().json_stringify_function(), JS::js_undefined(), value));

    // 2. If result is undefined, then throw a TypeError.
    if (result.is_undefined())
        return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Result of stringifying value must not be undefined"sv };

    // 3. Assert: result is a string.
    VERIFY(result.is_string());

    // 4. Return result.
    return result.as_string().deprecated_string();
}

// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-json-bytes
WebIDL::ExceptionOr<ByteBuffer> serialize_javascript_value_to_json_bytes(JS::VM& vm, JS::Value value)
{
    auto& realm = *vm.current_realm();

    // 1. Let string be the result of serializing a JavaScript value to a JSON string given value.
    auto string = TRY(serialize_javascript_value_to_json_string(vm, value));

    // 2. Return the result of running UTF-8 encode on string.
    // NOTE: LibJS strings are stored as UTF-8.
    return TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(string.bytes()));
}

}