How to parse JSON path in LUA?
-
Hi,
I'm working on new features for my Virtual Devices Plug-in. One of the things I want to add is the ability to poll an endpoint to get power consumption.
So, I want to store the URL and the JSON path in a variable, but I'm confused on how to dynamically parse JSON paths in LUA.
I have something like this in a string variable
data.meters[1].power
and I have to extract the corresponding value from the JSON I got over HTTP.
Any suggestion is very appreciated. Thanks.
-
Tricky.
If I understand correctly, this snippet of code may do what you need.
I have a string variable with that text in it, and a structure which includes that field (and others.) The code extracts the value of the given field...
local text = "data.meters[1].power" local struct = { foo = 42, data = { meters = { {power = math.pi}, {energy = 123}, 3, 4, 5 }, litres = 7, }, bung = "qwerty" } -- CODE STARTS HERE! local x = struct for field in text: gmatch "[^%.%[%]]+" do x = x[tonumber(field) or field] end print(x)
giving:
3.1415926535898
-
Tricky.
If I understand correctly, this snippet of code may do what you need.
I have a string variable with that text in it, and a structure which includes that field (and others.) The code extracts the value of the given field...
local text = "data.meters[1].power" local struct = { foo = 42, data = { meters = { {power = math.pi}, {energy = 123}, 3, 4, 5 }, litres = 7, }, bung = "qwerty" } -- CODE STARTS HERE! local x = struct for field in text: gmatch "[^%.%[%]]+" do x = x[tonumber(field) or field] end print(x)
giving:
3.1415926535898