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

No const operator[] #3

Open
NanotokLLC opened this issue Jul 13, 2019 · 0 comments
Open

No const operator[] #3

NanotokLLC opened this issue Jul 13, 2019 · 0 comments

Comments

@NanotokLLC
Copy link

If you try to examine a const JSONVar object using operator[] (e.g. auto foo = myVar["bar"]), the compiler will (obviously) not be able locate the nonexistent const operator[], but it won't quit there. Instead, it will (silently) beat your JSONVar sword into some unrelated plowshare and apply type type's const operator[] , with predictably nonsensical results.
For example, this code:

const JSONVar myVar1 = JSON.parse( "{\"foo\": \"bar\"}" );
auto myVar2 = myVar1[ "foo" ];
Serial.print( "foo: " );
Serial.println( myVar2 );

produces this output:
foo: f

If I add this method to JSONVar:

JSONVar JSONVar::operator[]( const char* key ) const
{
	if ( !cJSON_IsObject( _json ) )
	{
		return undefined;
	}
	cJSON* json = cJSON_GetObjectItemCaseSensitive( _json, key );
	if ( json == NULL )
	{
		json = cJSON_AddNullToObject( _json, key );
	}
	return JSONVar( json, _json );
}

then the output changes to a more reasonable
foo: "bar"

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

0 participants