Function: json-parse-buffer

json-parse-buffer is a function defined in json.c.

Signature

(json-parse-buffer &rest args)

Documentation

Read JSON object from current buffer starting at point.

Move point after the end of the object if parsing was successful. On error, don't move point.

The returned object will be a vector, list, hashtable, alist, or plist. Its elements will be the JSON null value, the JSON false value, t, numbers, strings, or further vectors, lists, hashtables, alists, or plists. If there are duplicate keys in an object, all but the last one are ignored.

If the current buffer doesn't contain a valid JSON object, the function signals an error of type json-parse-error.

The arguments ARGS are a list of keyword/argument pairs:

The keyword argument :object-type specifies which Lisp type is used to represent objects; it can be hash-table, alist or plist. It defaults to hash-table.

The keyword argument :array-type specifies which Lisp type is used to represent arrays; it can be array (the default) or list.

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.

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, args, &conf, true);

  ptrdiff_t point = PT_BYTE;
  struct json_read_buffer_data data = {.point = point};
  json_error_t error;
  json_t *object
    = json_load_callback (json_read_buffer_callback, &data,
                          JSON_DECODE_ANY | JSON_DISABLE_EOF_CHECK,
                          &error);

  if (object == NULL)
    json_parse_error (&error);

  /* Avoid leaking the object in case of further errors.  */
  record_unwind_protect_ptr (json_release_object, object);

  /* Convert and then move point only if everything succeeded.  */
  Lisp_Object lisp = json_to_lisp (object, &conf);

  /* Adjust point by how much we just read.  */
  point += error.position;
  SET_PT_BOTH (BYTE_TO_CHAR (point), point);

  return unbind_to (count, lisp);
}