nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.54k stars 6.69k forks source link

Convert Json to uint8_t #1008

Closed qvs5010 closed 6 years ago

qvs5010 commented 6 years ago

Hi How can I convert my JSON to a uint8_t? is this even possible?

uint8_t data[64] = theJsonData;

nlohmann commented 6 years ago

What should be the content? The byte representation of the JSON text?

qvs5010 commented 6 years ago

Hi

My json content looks like this {"lat": -24.673566818237305,"lon": 25.937171936035156}

Code:

static json theJsonData;

float float_lat = 0.0f;
float float_lon = 0.0f;
ifstream inf("/home/pi/ttn-ulm-node-dragino-master/data/geo.dat");
if (inf) {
         for (int i = 0; i < 2; i++) {
             std::string coord;
             getline(inf, coord);
           if (i == 0) {
             float_lat = stof(coord);
           }
           if (i == 1) {
             float_lon = stof(coord);
           }
        }
}else{
          printf("Failed!");
}

theJsonData["lat"] = float_lat;
theJsonData["lon"] = float_lon;

uint8_t data[64] = theJsonData; <-- geting error on compiling.

LMIC_setTxData2(1, data, sizeof(data)-1, 0);

theodelrieu commented 6 years ago

Functions cannot return C arrays, so you won't be able to do that. You could instead use std::array.

nlohmann commented 6 years ago

So theJsonData.dump(); would return a JSON text representation as std::string. From there, you can copy it into an std::array or uint8_t[] manually - assuming this is your usecase.

nlohmann commented 6 years ago

@qvs5010 Do you need further assistance?

qvs5010 commented 6 years ago

Hi thanks I did the following to get it right.

char str_W1[20];
char str_W2[20];

sprintf((char *) str_W1, "%.6f", float_lat);
sprintf((char *) str_W2, "%.6f", float_lon);

strcpy((char *) mydata,"{\"Lat\":");
strcat ((char *) mydata, str_W1);
strcat ((char *) mydata, ",\"Lon\":");
strcat ((char *) mydata, str_W2);
strcat ((char *) mydata, "}");

LMIC_setTxData2(1, mydata, strlen((char *)mydata), 0);
nlohmann commented 6 years ago

Thanks for checking back!

ashish-iottive commented 3 years ago

Thanks for checking back!

I want to convert a 110B Json file into unit8_t within limit upto 20 bytes . I am working on BLE Notification in ESP32 Arduino