NAME
jsonparse, jsonfree, jsonbyname, jsonstr – JSON parser

SYNOPSIS
#include <u.h>
#include <libc.h>
#include <json.h>
enum {
JSONNull,
JSONBool,
JSONNumber,
JSONString,
JSONArray,
JSONObject,
};
typedef struct JSONEl JSONEl;
struct JSONEl {
char *name;
JSON *val;
JSONEl *next;
};
typedef struct JSON JSON;
struct JSON
{
int t;
union {
double n;
char *s;
JSONEl *first;
};
};
JSON*     jsonparse(char *s);
void      jsonfree(JSON *j);
JSON*     jsonbyname(JSON *j, char *s);
char*     jsonstr(JSON *j);
int       JSONfmt(Fmt *f)
void      JSONfmtinstall(void);

DESCRIPTION
The JSON structure represents a variant json value. The variant type is stored in the t member of the structure. String values use s, booleans and numbers use the n members in the structure. Arrays and objects (dictionaries) are represented by a singly–linked list of JSONEl structures referred to from the first pointer in the JSON structure. Each JSONEl has a val pointer to the associated value and a next pointer to the next element in the array or object. Dictionary objects have the name member set to the key of the association.

A json object is parsed by calling jsonparse with a UTF–8 string of the json encoded data. On success, a non–nil pointer to a newly allocated JSON structure is returned. To free the parsed objects, jsonfree has to be called.

The jsonbyname function returns the associated value of a dictionary item.

The function jsonstr returns the string value of a json object or nil for any other object type.

JSONfmt is a print(2) formatting routine that prints a well–formatted JSON structure. It can be installed by hand but JSONfmtinstall installs it under the standard format character J. The header <json.h> contains a #pragma statement so the compiler can type–check uses of %J in print(2) format strings.

SOURCE
/sys/src/libjson

DIAGNOSTICS
The functions jsonparse, jsonbyname and jsonstr return nil on error and set an error string (see errstr(2)).