Sujet : Re: Which newsgroup for json parsing?
De : nospam (at) *nospam* please.ty (jak)
Groupes : comp.lang.cDate : 09. May 2024, 14:18:11
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v1iiee$m05n$1@dont-email.me>
References : 1
User-Agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0 SeaMonkey/2.53.18.2
Josef Möllers ha scritto:
Hi all,
I am trying to parse a json string received through MQTT from a "Shelly Plug S", e.g.
{"id":0, "source":"button", "output":true, "apower":0.0, "voltage":237.9, "current":0.000, "aenergy":{"total":0.000,"by_minute":[0.000,0.000,0.000],"minute_ts":1715172119},"temperature":{"tC":41.1, "tF":106.0}}
I am trying to use libjson-glib but I can't figure out what to use as the first argument to json_gobject_from_data()!
I am also looking at libjson-c but cannot find any examples that could guide me.
Thanks in advance,
Josef
Hi,
from your post I can't understand if you are writing
production code or just for yourself, nor if you intend to
deepen your knowledge of json or just acquire the data of
interest from the json. If you are interested in the data and
the code is for you, I can suggest an inelegant but effective
way unless you want to monitor the data in a fast loop. I
would suggest you let the jq command line do the work for
you and grab its output via popen. jq is a command for *nix
but you can also find it for windows. here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
int main()
{
FILE *fp;
char from_plug[] = "{\"id\":0, \"source\" : \"button\", \"output\" : true, \"apower\" : 0.0, "
"\"voltage\": 237.9, \"current\": 0.000, \"aenergy\":{ \"total\" : 0.000, "
"\"by_minute\": [0.000,0.000,0.000], \"minute_ts\": 1715172119}, "
"\"temperature\":{ \"tC\": 41.1, \"tF\": 106.0}}";
char echo_fmt[] = "cmd /c echo %s | jq .temperature.tC,.voltage,.source";
size_t cmd_len = snprintf(NULL, 0, echo_fmt, from_plug) + 1;
char cmd[cmd_len];
double temp, volt;
char source[20];
snprintf(cmd, cmd_len, echo_fmt, from_plug);
if((fp = popen(cmd, "r")) != NULL)
{
fscanf(fp, " %lf %lf %*[\"]%[^\"] ", &temp, &volt, source);
setlocale(LC_ALL, "");
wprintf(L"\n"
L"temperature: %6.2lf\u00B0\n"
L"voltage: %6.2lf v\n"
L"source: %hs\n", temp, volt, source);
pclose(fp);
}
else
perror("popen");
return 0;
}
output:
temperature: 41.10°
voltage: 237.90 v
source: button