diff --git a/example-01.c b/example-01.c index e4f5049..939bce2 100644 --- a/example-01.c +++ b/example-01.c @@ -60,13 +60,12 @@ int main( void ) { char const* firstNameVal = json_getValue( firstName ); printf( "Fist Name: %s.\n", firstNameVal ); - json_t const* lastName = json_getProperty( json, "lastName" ); - if ( !lastName || JSON_TEXT != json_getType( lastName ) ) { + char const* lastName = json_getPropertyValue( json, "lastName" ); + if ( !lastName ) { puts("Error, the last name property is not found."); return EXIT_FAILURE; - } - char const* lastNameVal = json_getValue( lastName ); - printf( "Last Name: %s.\n", lastNameVal ); + } + printf( "Last Name: %s.\n", lastName ); json_t const* age = json_getProperty( json, "age" ); if ( !age || JSON_INTEGER != json_getType( age ) ) { @@ -85,11 +84,8 @@ int main( void ) { json_t const* phone; for( phone = json_getChild( phoneList ); phone != 0; phone = json_getSibling( phone ) ) { if ( JSON_OBJ == json_getType( phone ) ) { - json_t const* number = json_getProperty( phone, "number" ); - if ( number ) { - char const* numberVal = json_getValue( number ); - printf( "Number: %s.\n", numberVal ); - } + char const* phoneNumber = json_getPropertyValue( phone, "number" ); + if ( phoneNumber ) printf( "Number: %s.\n", phoneNumber ); } } diff --git a/makefile b/makefile index 4616b92..800cd28 100644 --- a/makefile +++ b/makefile @@ -1,6 +1,6 @@ -build: example-01.exe example-02.exe test.exe +build: example-01.exe example-02.exe clean: rm -rf *.o diff --git a/tiny-json.c b/tiny-json.c index fb30922..97dc533 100644 --- a/tiny-json.c +++ b/tiny-json.c @@ -36,6 +36,13 @@ json_t const* json_getProperty( json_t const* obj, char const* property ) { return 0; } +/* Search a property by its name in a JSON object and return its value. */ +char const* json_getPropertyValue( json_t const* obj, char const* property ) { + json_t const* field = json_getProperty( obj, property ); + if ( !field ) return 0; + return json_getValue( field ); +} + /* Internal prototypes: */ static char* _goWhiteSpace( char* str ); static char* _goNum( char* str ); diff --git a/tiny-json.h b/tiny-json.h index db5053e..cb70bd8 100644 --- a/tiny-json.h +++ b/tiny-json.h @@ -95,6 +95,14 @@ static inline json_t const* json_getSibling( json_t const* json ) { * @retval Null pointer if not found. */ json_t const* json_getProperty( json_t const* obj, char const* property ); + +/** Search a property by its name in a JSON object and return its value. + * @param obj A valid handler of a json object. Its type must be JSON_OBJ. + * @param property The name of property to get. + * @retval If found a pointer to null-terminated string with the value. + * @retval Null pointer if not found. */ +char const* json_getPropertyValue( json_t const* obj, char const* property ); + /** Get the first property of a JSON object or array. * @param json A valid handler of a json property. * Its type must be JSON_OBJ or JSON_ARRAY.