Function: json-serialize

json-serialize is a function defined in json.c.

Signature

(json-serialize OBJECT &rest ARGS)

Documentation

Return the JSON representation of OBJECT as a string.

OBJECT must be t, a number, string, vector, hashtable, alist, plist, or the Lisp equivalents to the JSON null and false values, and its elements must recursively consist of the same kinds of values. t will be converted to the JSON true value. Vectors will be converted to JSON arrays, whereas hashtables, alists and plists are converted to JSON objects. Hashtable keys must be strings without embedded null characters and must be unique within each object. Alist and plist keys must be symbols; if a key is duplicate, the first instance is used.

The Lisp equivalents to the JSON null and false values are configurable in the arguments ARGS, a list of keyword/argument pairs:

The keyword argument :null-object specifies which object to use to represent a JSON null value. It defaults to :null.

The keyword argument :false-object specifies which object to use to represent a JSON false value. It defaults to :false.

In you specify the same value for :null-object and :false-object, a potentially ambiguous situation, the JSON output will not contain any JSON false values.

Probably introduced at or before Emacs version 27.1.

Source Code

// Defined in /usr/src/emacs/src/json.c
{
  ptrdiff_t count = SPECPDL_INDEX ();

#ifdef WINDOWSNT
  if (!json_initialized)
    {
      Lisp_Object status;
      json_initialized = init_json_functions ();
      status = json_initialized ? Qt : Qnil;
      Vlibrary_cache = Fcons (Fcons (Qjson, status), Vlibrary_cache);
    }
  if (!json_initialized)
    Fsignal (Qjson_unavailable,
	     list1 (build_unibyte_string ("jansson library not found")));
#endif

  struct json_configuration conf =
    {json_object_hashtable, json_array_array, QCnull, QCfalse};
  json_parse_args (nargs - 1, args + 1, &conf, false);

  json_t *json = lisp_to_json (args[0], &conf);
  record_unwind_protect_ptr (json_release_object, json);

  char *string = json_dumps (json, JSON_COMPACT | JSON_ENCODE_ANY);
  if (string == NULL)
    json_out_of_memory ();
  record_unwind_protect_ptr (json_free, string);

  return unbind_to (count, build_string_from_utf8 (string));
}