Izanatos
Izanatos

Reputation: 33

Lua: String.match and Regex

I have a json output but unfortunalty, I cannot parse it with any json library as the devices I am running my script on cannot be update.

Depending on the device model I am getting slightly different outputs(note the space before the colon):

json_output1='{ "var1" : "result1", "var2" : "result2", "var3" : "result3", "var4" : "10" }'
or
json_output2='{ "var1": "result1", "var2": "result2", "var3": "result3", "var4": "10" }'

I found a way to parse this as a string with string:match() and regex like so

var1, var2, var3, var4 = json_ouptut1:match('.+"var1" : "([^"]+)"'
               .. '.+"var2" : "([^"]+)"'
               .. '.+"var3" : "([^"]+)"'
               .. '.+"var4" : "([^"]+)"')
print(var2) 
--[[ OUTOUT
$lua main.lua
result2
--]]

This work and I am happy with it but it only work for one or the other output because of the space before the colon.

Any idea how I could have this working for either string ?

thanks

Upvotes: 1

Views: 3025

Answers (2)

lhf
lhf

Reputation: 72312

Try this code. It works for both inputs. Adapt as needed.

for k,v in json_output:gmatch('"(.-)"%s*:%s*"(.-)"') do
    print(k,v)
end

The key here is to use %s* to skip any runs of whitespace, even empty ones.

Upvotes: 1

Nifim
Nifim

Reputation: 5031

You can use %s? to allow the pattern to look for 1 or 0 spaces.

json_output1='{ "var1" : "result1", "var2" : "result2", "var3" : "result3", "var4" : "10" }'
json_output2='{ "var1": "result1", "var2": "result2", "var3": "result3", "var4": "10" }'

var1, var2, var3, var4 = json_output1:match('.+"var1"%s?: "([^"]+)"'
               .. '.+"var2"%s?: "([^"]+)"'
               .. '.+"var3"%s?: "([^"]+)"'
               .. '.+"var4"%s?: "([^"]+)"')
print(var2)

var1, var2, var3, var4 = json_output2:match('.+"var1"%s?: "([^"]+)"'
               .. '.+"var2"%s?: "([^"]+)"'
               .. '.+"var3"%s?: "([^"]+)"'
               .. '.+"var4"%s?: "([^"]+)"')
print(var2)

Here is a good resource for information on Lua patterns: Understanding Lua Patterns

Upvotes: 1

Related Questions