Function encodeAsJson

  • Encode the value into a JSON string, if the provided value is a string this will encode any character that is not an alpha, numeric, space or some special characters as \uXXXX and will always be returned wrapped in double quotes "xxx", if the value is any other object it will be encoded using JSON.stringify() and if there is an exception encoding with JSON.stringify() it will return the exception as a string using dumpObj().

    Type Parameters

    • T

    Parameters

    • value: T

      The value to be encoded as JSON

    • Optional format: number | boolean

      Identifies whether the JSON value should be formatted when an object

      • true - Format with 4 spaces
      • 'number' - The number of spaces to format with
      • false (or not Truthy) - Do not format*

    Returns string

    A JSON encoded string representation of the value.

    Since

    0.9.0

    Example

    // String values
    encodeAsJson("abc.123"); // "\"abc.123\""
    encodeAsJson("321-abc"); // "\"321-abc\""
    encodeAsJson("Hello darkness, my \"old\" friend..."); // "\"Hello darkness, my \\\"old\\\" friend...\""
    encodeAsJson("Hello: Darkness"); // "\"Hello: Darkness\""
    encodeAsJson("Hello\\u003A Darkness"); // "\"Hello\\\\u003A Darkness\""
    encodeAsJson("`!@#$%^&*()_-+=[]{}:;'<>?"); // "\"\\u0060!@#$%^&*()_-+=[]{}:;\\u0027<>?\""
    encodeAsJson("0"); // "\"0\""
    encodeAsJson("1"); // "\"1\""

    encodeAsJson([]); // "[]"
    encodeAsJson(["A"]); // "[\"A\"]"
    encodeAsJson([0]); // "[0]"
    encodeAsJson([false]); // "[false]"
    encodeAsJson(new Array(1)); // "[null]"
    encodeAsJson(true); // "true",
    encodeAsJson(false); // "false"

    encodeAsJson({}); // "{}"
    encodeAsJson({ Hello: "Darkness" }); // "{\"Hello\":\"Darkness\"}");