Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Barenboim opened this issue May 6, 2023 · 0 comments
Open

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

Barenboim opened this issue May 6, 2023 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@Barenboim
Copy link
Owner

Barenboim commented May 6, 2023

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 Barenboim added the documentation Improvements or additions to documentation label May 6, 2023
@Barenboim Barenboim changed the title JSON value can be casted to it's data type directly. JSON value can be cast to it's data type directly. May 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant