Skip to content

JSON values are not escaped (e.g. "\"") #17

Description

@sisidra

mmdb_record returns malformed JSON because string values are not escaped.

Here is an example using ipinfo_lite.mmdb:

select mmdb_record('ipinfo_lite.mmdb', '176.100.8.218', '');
mmdb_record
{"as_domain":"volz.ua","as_name":""SCIENTIFIC-INDUSTRIAL FIRM "VOLZ" LIMITED LIABILITY COMPANY","asn":"AS12963","continent":"Europe","continent_code":"EU","country":"Ukraine","country_code":"UA"}
My non-expert analysis

Quick glance at the code:
result.value.format is not escaping strings as per documentation.

Replacing it with quick and dirty patched format_json returns valid JSON, for example:

// ...format_json(result.value, &w)...

/// Strings *are* escaped.
pub fn format_json(self: maxminddb.any.Value, writer: anytype) !void {
    switch (self) {
        .string => |s| {
            try std.json.Stringify.value(s, .{}, writer);
        },
        .int32 => |v| try writer.print("{}", .{v}),
        .uint16, .uint32, .uint64 => |v| try writer.print("{}", .{v}),
        .uint128 => |v| try writer.print("\"{}\"", .{v}),
        .double => |v| try writer.print("{d}", .{v}),
        .float => |v| try writer.print("{d}", .{v}),
        .boolean => |v| try writer.writeAll(if (v) "true" else "false"),
        .array => |items| {
            try writer.writeByte('[');

            for (items, 0..) |item, i| {
                if (i > 0) {
                    try writer.writeByte(',');
                }

                try format_json(item, writer);
            }

            try writer.writeByte(']');
        },
        .map => |entries| {
            try writer.writeByte('{');

            for (entries, 0..) |entry, i| {
                if (i > 0) {
                    try writer.writeByte(',');
                }

                try std.json.Stringify.value(entry.key, .{}, writer);
                try writer.writeByte(':');
                try format_json(entry.value, writer);
            }

            try writer.writeByte('}');
        },
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions