json-parser icon indicating copy to clipboard operation
json-parser copied to clipboard

JSON value can be cast to it's data type directly.

Open Barenboim opened this issue 1 year ago • 0 comments

A JSON value can be cast directly to it's data:

int main()
{
    json_value_t *val = json_value_parse("...");

    // The following castings are legal if 'val' is the corresponding type.
    const char *str = *(const char **)val;          // equal to: str = json_value_string(val);
    double num = *(double *)val;                    // equal to: num = json_value_number(val);
    json_object_t *obj = (json_object_t *)val;      // equal to: obj = json_value_object(val);
    json_array_t *arr = (json_array_t *)val;        // equal to: arr = json_value_array(val);
}

Because the JSON value shares the same address with it's data, and this was designed on purpose and you may always make use of this feature. In json_parser.c, the JSON value structure is defined as:

struct __json_value
{
	union
	{
		char *string;
		double number;
		json_object_t object;
		json_array_t array;
	} value;
	int type;
};

The JSON value's data are always the first fields, so the addresses of them are identical to the value. You can cast reversely as well by casting an object or an array to a JSON value.

Barenboim avatar May 06 '23 15:05 Barenboim