1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.