Tiny-json 是一个 C 解析器,它允许您以最简单的方式访问数字字段的字符串表示形式。只需请求一个 JSON 属性,它就会返回一个指向以空值结尾的指针。
https://github.com/rafagafe/tiny-json
#include <stdio.h>
#include "tiny-json.h"
int main( int argc, char** argv ) {
char str[] = "{\"accuracy\":654,\"real\":2.54e-3}";
// In the example only 3 is needed. For root and two fields.
json_t mem[ 3 ];
json_t const* root = json_create( str, mem, sizeof mem / sizeof *mem );
if ( !root ) {
fputs( "Cannot create a JSON.\n", stderr );
return 1;
}
{ // You can get the primitive values as text format:
char const* accuracy = json_getPropertyValue( root, "accuracy" );
if ( !accuracy ) {
fputs( "The filed 'accuracy' is not found.\n", stderr );
return 1;
}
printf( "The accuracy value: %s\n", accuracy );
char const* real = json_getPropertyValue( root, "real" );
if ( !real ) {
fputs( "The filed 'real' is not found.\n", stderr );
return 1;
}
printf( "The real value: %s\n", real );
}
{ // You can check the type of a field and get its value in binary format:
json_t const* accuracy = json_getProperty( root, "accuracy" );
if ( !accuracy ) {
fputs( "The filed 'accuracy' is not found.\n", stderr );
return 1;
}
if( json_getType( accuracy ) != JSON_INTEGER ) {
fputs( "The filed 'accuracy' is not an integer.\n", stderr );
return 1;
}
// Get the value in binary format:
long long accuracyVal = json_getInteger( accuracy );
printf( "The accuracy value: %lld\n", accuracyVal );
// Get the value in text format:
char const* accuracyTxt = json_getValue( accuracy );
printf( "The accuracy value: %s\n", accuracyTxt );
json_t const* real = json_getProperty( root, "real" );
if ( !accuracy ) {
fputs( "The filed 'real' is not found.\n", stderr );
return 1;
}
if( json_getType( real ) != JSON_REAL ) {
fputs( "The filed 'real' is not a real.\n", stderr );
return 1;
}
// Get the value in binary format:
double realVal = json_getReal( real );
printf( "The real value: %f\n", realVal );
// Get the value in text format:
char const* realTxt = json_getValue( real );
printf( "The real value: %s\n", realTxt );
}
return 0;
}