cJSON output error

Use NRF52840 and SDK_17.1.0.

Input:

memcpy(gps_location.la,"12.345",6);
memcpy(gps_location.lo,"678.345",7); 

void test_json()
{
  wifi_scan.index = 0;
  memcpy(gps_location.la,"12.345",6); 
  memcpy(gps_location.lo,"678.345",7); 
  memcpy(ap_info[wifi_scan.index].mac,"12:34:56:78:90:ab",17);
  memcpy(ap_info[wifi_scan.index].rssi,"-99",3);
  wifi_scan.index++;
  memcpy(ap_info[wifi_scan.index].mac,"ff:ff:ff:ff:ff:ff",17);
  memcpy(ap_info[wifi_scan.index].rssi,"-9",2);
  wifi_scan.index++;
  memcpy(lte_msg.cid,"123456",6); 
  memcpy(lte_msg.lac,"abcdef",6); 
}

Output:

"la": 12.345000256,
"lo": 678.344970688,

This is code:

47004.ble_app_uart.zip

  • supplement:

    Print the above log code.

    void json_config_result_objects(void)
    {
        cJSON *root = NULL ,*param = NULL;
        float ftem;
        int item;
        data_to_json();
        memset( json_result, 0, sizeof(json_result) );
        root = cJSON_CreateObject();
        ftem = atof(json_data.gps.la);
        cJSON_AddNumberToObject( root ,"la" , ftem ); 
        ftem = atof(json_data.gps.lo);   
        cJSON_AddNumberToObject( root ,"lo" , ftem );
        ftem = 0.00;
        cJSON_AddNumberToObject( root ,"pr" , ftem );
        cJSON_AddItemToObject( root ,"wifi", param = cJSON_CreateObject() );
        for( uint8_t i=0; i<json_data.scan.index; i++ )
        {
            cJSON_AddStringToObject( param ,"m", json_data.wifi[i].mac  );
            //item = atoi(json_data.wifi[i].rssi);
            //cJSON_AddNumberToObject( param ,"s", item );
        }
    
        cJSON_AddStringToObject( root ,"bat" , "00.0" );
        cJSON_AddStringToObject( root ,"st" , "00.0" );
        cJSON_AddStringToObject( root ,"fw" , "00.0" );
        cJSON_AddStringToObject( root ,"cid" , json_data.lte.cid );
        cJSON_AddStringToObject( root ,"lac" ,json_data.lte.lac );
        cJSON_AddStringToObject( root ,"chg" , "00" );
        cJSON_AddStringToObject( root ,"ev" , "00" );
        char *objects = cJSON_Print(root);
        memcpy( json_result, objects, strlen(objects) );
        NRF_LOG_INFO( "%s", json_result );
        cJSON_Delete(root);
        cJSON_free(objects);
    }

  • Hi John,

    To avoid misunderstandings: What is the error with the JSON output?

    Regards,
    Sigurd Hellesvik

  • Input la="12.345"&lo="678.345",Output la=12.345000256,lo=678.344970688.

    It should be:la=12.345&lo=678.345.

  • Hi,

    Your error is likely due to float precision.

    For cJSON, the issue seems to be in the print function. Have a look at this function in your cJSON.c file:

    static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)

    As a workaround, you could try to change the decimal places configured in this function.

    Regards,
    Sigurd Hellesvik

Related