跳转到内容

std.json.dynamic

标准库Zig 0.17.0官方原文
源码std/json/dynamic.zig

第 1 行

std.json.dynamic.Allocator

别名

第 5 行

别名目标 std.mem.Allocator

std.json.dynamic.ArenaAllocator

别名

第 3 行

别名目标 std.heap.ArenaAllocator

std.json.dynamic.Array

类型

第 14 行

std.json.dynamic.debug

别名

第 2 行

别名目标 std.debug

std.json.dynamic.handleCompleteValue

函数

第 133 行

fn handleCompleteValue(stack: *Array, allocator: Allocator, source: anytype, value_: Value, options: ParseOptions) !?Value

参数

stack: *Array
allocator: Allocator
value_: Value
options: ParseOptions

std.json.dynamic.isNumberFormattedLikeAnInteger

别名

第 11 行

别名目标 std.json.Scanner.isNumberFormattedLikeAnInteger

std.json.dynamic.json

别名

第 6 行

别名目标 std.json

std.json.dynamic.ObjectMap

类型

第 13 行

std.json.dynamic.ParseError

别名

第 9 行

别名目标 std.json.static.ParseError

std.json.dynamic.ParseOptions

别名

第 8 行

别名目标 std.json.static.ParseOptions

std.json.dynamic.std

别名

第 1 行

别名目标 std

std.json.dynamic.StringArrayHashMap

别名

第 4 行

别名目标 std.array_hash_map.String

std.json.dynamic.Value

容器

第 20 行

表示任意 JSON 值,可能包含其他 JSON 值。 .float 值可能只是原始值的近似值。 可用 .number_string 值表示任意精度数字。 另见 std.json.ParseOptions.parse_numbers。

字段

null
bool: bool
integer: i64
float: f64
number_string: []const u8
string: []const u8
array: Array
object: ObjectMap

std.json.dynamic.Value.dump

函数

第 49 行

pub fn dump(v: Value) void

参数

v: Value

std.json.dynamic.Value.jsonParse

函数

第 76 行

pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This()

参数

allocator: Allocator
options: ParseOptions

std.json.dynamic.Value.jsonParseFromValue

函数

第 126 行

pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) !@This()

参数

allocator: Allocator
source: Value
options: ParseOptions

std.json.dynamic.Value.jsonStringify

函数

第 55 行

pub fn jsonStringify(value: @This(), jws: anytype) !void

参数

value: @This()

std.json.dynamic.Value.parseFromNumberSlice

函数

第 30 行

pub fn parseFromNumberSlice(s: []const u8) Value

参数

s: []const u8
源码

std/json/dynamic.zig

const std = @import("std");
const debug = std.debug;
const ArenaAllocator = std.heap.ArenaAllocator;
const StringArrayHashMap = std.array_hash_map.String;
const Allocator = std.mem.Allocator;
const json = std.json;

const ParseOptions = @import("./static.zig").ParseOptions;
const ParseError = @import("./static.zig").ParseError;

const isNumberFormattedLikeAnInteger = @import("Scanner.zig").isNumberFormattedLikeAnInteger;

pub const ObjectMap = StringArrayHashMap(Value);
pub const Array = std.array_list.Managed(Value);

/// 表示任意 JSON 值,可能包含其他 JSON 值。
/// .float 值可能只是原始值的近似值。
/// 可用 .number_string 值表示任意精度数字。
/// 另见 `std.json.ParseOptions.parse_numbers`。
pub const Value = union(enum) {
    null,
    bool: bool,
    integer: i64,
    float: f64,
    number_string: []const u8,
    string: []const u8,
    array: Array,
    object: ObjectMap,

    pub fn parseFromNumberSlice(s: []const u8) Value {
        if (!isNumberFormattedLikeAnInteger(s)) {
            const f = std.fmt.parseFloat(f64, s) catch unreachable;
            if (std.math.isFinite(f)) {
                return Value{ .float = f };
            } else {
                return Value{ .number_string = s };
            }
        }
        if (std.fmt.parseInt(i64, s, 10)) |i| {
            return Value{ .integer = i };
        } else |e| {
            switch (e) {
                error.Overflow => return Value{ .number_string = s },
                error.InvalidCharacter => unreachable,
            }
        }
    }

    pub fn dump(v: Value) void {
        const stderr = std.debug.lockStderr(&.{});
        defer std.debug.unlockStderr();
        json.Stringify.value(v, .{}, &stderr.file_writer.interface) catch return;
    }

    pub fn jsonStringify(value: @This(), jws: anytype) !void {
        switch (value) {
            .null => try jws.write(null),
            .bool => |inner| try jws.write(inner),
            .integer => |inner| try jws.write(inner),
            .float => |inner| try jws.write(inner),
            .number_string => |inner| try jws.print("{s}", .{inner}),
            .string => |inner| try jws.write(inner),
            .array => |inner| try jws.write(inner.items),
            .object => |inner| {
                try jws.beginObject();
                var it = inner.iterator();
                while (it.next()) |entry| {
                    try jws.objectField(entry.key_ptr.*);
                    try jws.write(entry.value_ptr.*);
                }
                try jws.endObject();
            },
        }
    }

    pub fn jsonParse(allocator: Allocator, source: anytype, options: ParseOptions) ParseError(@TypeOf(source.*))!@This() {
        // 栈的语法为:
        //  (.array | .object .string)*
        var stack = Array.init(allocator);
        defer stack.deinit();

        while (true) {
            // 断言栈顶的栈语法。
            debug.assert(stack.items.len == 0 or
                stack.items[stack.items.len - 1] == .array or
                (stack.items[stack.items.len - 2] == .object and stack.items[stack.items.len - 1] == .string));

            switch (try source.nextAllocMax(allocator, .alloc_always, options.max_value_len.?)) {
                .allocated_string => |s| {
                    return try handleCompleteValue(&stack, allocator, source, Value{ .string = s }, options) orelse continue;
                },
                .allocated_number => |slice| {
                    if (options.parse_numbers) {
                        return try handleCompleteValue(&stack, allocator, source, Value.parseFromNumberSlice(slice), options) orelse continue;
                    } else {
                        return try handleCompleteValue(&stack, allocator, source, Value{ .number_string = slice }, options) orelse continue;
                    }
                },

                .null => return try handleCompleteValue(&stack, allocator, source, .null, options) orelse continue,
                .true => return try handleCompleteValue(&stack, allocator, source, Value{ .bool = true }, options) orelse continue,
                .false => return try handleCompleteValue(&stack, allocator, source, Value{ .bool = false }, options) orelse continue,

                .object_begin => {
                    switch (try source.nextAllocMax(allocator, .alloc_always, options.max_value_len.?)) {
                        .object_end => return try handleCompleteValue(&stack, allocator, source, Value{ .object = .empty }, options) orelse continue,
                        .allocated_string => |key| {
                            try stack.appendSlice(&[_]Value{
                                Value{ .object = .empty },
                                Value{ .string = key },
                            });
                        },
                        else => unreachable,
                    }
                },
                .array_begin => {
                    try stack.append(Value{ .array = Array.init(allocator) });
                },
                .array_end => return try handleCompleteValue(&stack, allocator, source, stack.pop().?, options) orelse continue,

                else => unreachable,
            }
        }
    }

    pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) !@This() {
        _ = allocator;
        _ = options;
        return source;
    }
};

fn handleCompleteValue(stack: *Array, allocator: Allocator, source: anytype, value_: Value, options: ParseOptions) !?Value {
    if (stack.items.len == 0) return value_;
    var value = value_;
    while (true) {
        // 断言栈顶的栈语法。
        debug.assert(stack.items[stack.items.len - 1] == .array or
            (stack.items[stack.items.len - 2] == .object and stack.items[stack.items.len - 1] == .string));
        switch (stack.items[stack.items.len - 1]) {
            .string => |key| {
                // 栈:[..., .object, .string]
                _ = stack.pop();

                // 栈:[..., .object]
                var object = &stack.items[stack.items.len - 1].object;

                const gop = try object.getOrPut(allocator, key);
                if (gop.found_existing) {
                    switch (options.duplicate_field_behavior) {
                        .use_first => {},
                        .@"error" => return error.DuplicateField,
                        .use_last => {
                            gop.value_ptr.* = value;
                        },
                    }
                } else {
                    gop.value_ptr.* = value;
                }

                // 不能让栈停留在此无效状态,
                // 因此返回之前必须处理下一个词元。
                switch (try source.nextAllocMax(allocator, .alloc_always, options.max_value_len.?)) {
                    .object_end => {
                        // 此对象已完整。
                        value = stack.pop().?;
                        // 现在已有完整值,因此实际进行递归。
                        if (stack.items.len == 0) return value;
                        continue;
                    },
                    .allocated_string => |next_key| {
                        // 我们又得到了一把密钥。
                        try stack.append(Value{ .string = next_key });
                        // 栈:[..., .object, .string]
                        return null;
                    },
                    else => unreachable,
                }
            },
            .array => |*array| {
                // stack: [..., .array]
                try array.append(value);
                return null;
            },
            else => unreachable,
        }
    }
}

test {
    _ = @import("dynamic_test.zig");
}