Sample code for 30+ languages & platforms
C

JSON: Miscellaneous Operations

See more JSON Examples

Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
   "alphabet": "abcdefghijklmnopqrstuvwxyz",
   "sampleData" : {
           "pi": 3.14,
	   "apple": "juicy",
	   "hungry": true,
	   "withoutValue": null,
           "answer": 42
          
	}
}

Chilkat C Downloads

C
#include <C_CkJsonObject.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJsonObject json;
    HCkJsonObject sampleData;

    success = FALSE;

    json = CkJsonObject_Create();
    CkJsonObject_putEmitCompact(json,FALSE);

    // Assume the file contains the data as shown above..
    success = CkJsonObject_LoadFile(json,"qa_data/json/sample2.json");
    if (success == FALSE) {
        printf("%s\n",CkJsonObject_lastErrorText(json));
        CkJsonObject_Dispose(json);
        return;
    }

    // Get the "sampleData" object:
    sampleData = CkJsonObject_Create();
    CkJsonObject_ObjectOf2(json,"sampleData",sampleData);

    // Demonstrate BoolAt and BoolOf
    printf("hungry: %d\n",CkJsonObject_BoolOf(sampleData,"hungry"));
    printf("hungry: %d\n",CkJsonObject_BoolAt(sampleData,2));

    // StringOf returns the value as a string regardless of it's actual type:
    printf("pi: %s\n",CkJsonObject_stringOf(sampleData,"pi"));
    printf("answer: %s\n",CkJsonObject_stringOf(sampleData,"answer"));
    printf("withoutValue: %s\n",CkJsonObject_stringOf(sampleData,"withoutValue"));
    printf("hungry: %s\n",CkJsonObject_stringOf(sampleData,"hungry"));

    // Demonstrate IsNullOf / IsNullAt
    printf("withoutValue is null? %d\n",CkJsonObject_IsNullOf(sampleData,"withoutValue"));
    printf("withoutValue is null? %d\n",CkJsonObject_IsNullAt(sampleData,3));
    printf("apple is null? %d\n",CkJsonObject_IsNullOf(sampleData,"apple"));
    printf("apple is null? %d\n",CkJsonObject_IsNullAt(sampleData,1));

    // IntOf
    printf("answer: %d\n",CkJsonObject_IntOf(sampleData,"answer"));

    // SetNullAt, SetNullOf
    // Set "pi" to null
    success = CkJsonObject_SetNullAt(sampleData,0);
    // Set "answer" to null
    success = CkJsonObject_SetNullOf(sampleData,"answer");

    // Show the changes:
    printf("%s\n",CkJsonObject_emit(json));

    // Restore pi and apple:
    success = CkJsonObject_SetNumberAt(sampleData,0,"3.14");
    success = CkJsonObject_SetNumberOf(sampleData,"answer","42");

    // Show the changes:
    printf("%s\n",CkJsonObject_emit(json));

    // Add a null value named "afterApple" just after "apple"
    success = CkJsonObject_AddNullAt(sampleData,2,"afterApple");

    // Add a boolean value just after "pi"
    success = CkJsonObject_AddBoolAt(sampleData,1,"afterPi",FALSE);

    // Examine the changes..
    printf("%s\n",CkJsonObject_emit(json));


    CkJsonObject_Dispose(json);
    CkJsonObject_Dispose(sampleData);

    }