Skip to content

Change font_to_json to return string #9

@jlarmstrongiv

Description

@jlarmstrongiv

Currently, font_to_json:

I've added an (untested) "font_to_json" function to the web bindings. Takes a U8 buffer, returns a JS object (not a JSON string, like the other functions). Let me know how you get on with it.

For consistency, it would be nice for the function to return a string.

In addition, when objects and arrays are preferred over maps and sets, the result requires conversion too.

Here’s an example function to remove maps and sets from the result, which is then safe to JSON.stringify:

export type JsonValue =
  | string
  | number
  | boolean
  | null
  | JsonValue[]
  | { [key: string | number | symbol]: JsonValue };

export function castMapsAndSets(input: JsonValue): JsonValue {
  if (input instanceof Map) {
    const object: Record<string | number | symbol, JsonValue> = {};
    for (const [key, value] of input.entries()) {
      // cast key to string, as object keys must be strings or symbols,
      // and JSON.stringify cannot stringify symbols
      object[String(key)] = castMapsAndSets(value);
    }
    return object;
  }

  if (input instanceof Set) {
    return [...input].map(castMapsAndSets);
  }

  if (Array.isArray(input)) {
    return input.map(castMapsAndSets);
  }

  if (input !== null && typeof input === "object") {
    const object: Record<string | number | symbol, JsonValue> = {};
    for (const [key, value] of Object.entries(input)) {
      object[key] = castMapsAndSets(value);
    }
    return object;
  }

  // otherwise, it is a primitive type (string | number | boolean | null)
  return input;
}

EDIT: one possible downside encountered by converting CJK fonts in other tools like TTX is that some font files go beyond the expected string size / json limit in JavaScript. So perhaps it should be a separate method, like font_to_json_string

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions