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

C Constants and cJSON #926

Open
almostobvious opened this issue Jan 29, 2025 · 0 comments
Open

C Constants and cJSON #926

almostobvious opened this issue Jan 29, 2025 · 0 comments

Comments

@almostobvious
Copy link

This is more of a question than issue but can't find a better way to ask it...

I have a bit of code that parses json to create some objects. Among the data being parsed are fields that can take int, but in the codebase there are specific constants that are used for these fields. Now what I'd like to do is to have the label of the constant inside JSON instead of it's integer value.

A simple example is with an enum:

typedef enum { title = 0, heading, normal} textSize;

I can parse this manually with:

int getJsonTextSizeEnum(cJSON * json, const char* label, int defaultValue ){
	cJSON * elem = cJSON_GetObjectItemCaseSensitive(json, label);
	if ( elem == NULL ) return defaultValue;
	if (  cJSON_IsString(elem) ) {
		if ( strcmp("title", elem->valuestring) == 0 ) return title;
		if ( strcmp("heading", elem->valuestring) == 0 ) return heading;
		if ( strcmp("normal", elem->valuestring) == 0 ) return normal;
	} else{
		return getJsonInt(json, label, defaultValue);
	}
	return defaultValue;
}

This makes for usable and readable json at the expense of a bit extra code.

But what happens when I have 100s of values to translate? Say, for example I want to specify the icon from fontawesome. Ideally, I'd like to have meaningful icon name in json (ICON_FA_FLASK), not an unintelligible codepoint ("\xef\x83\x83") - without hundreds of lines of code.

Any suggestions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant