Skip to content

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

@Barenboim

Description

@Barenboim

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions