json до lua с несколькими жалами backsla sh и точка - PullRequest
0 голосов
/ 24 февраля 2020

Здравствуйте, я пытаюсь использовать Json из моей стиральной машины с lua. Это для визуализации samsung в Domoitcz.

Часть Json, что я получаю от https://api.smartthings.com/v1/devices/abcd-1234-abcd, это:

"main": {
"washerJobState": {
            "value": "wash"
},
"mnhw": {
            "value": "1.0"
},
"data": {
          "value": "{
                \"payload\":{
                 \"x.com.samsung.da.state\":\"Run\",\"x.com.samsung.da.delayEndTime\":\"00:00:00\",\"x.com.samsung.da.remainingTime\":\"01:34:00\",\"if\":[\"oic.if.baseline\",\"oic.if.a\"],\"x.com.samsung.da.progressPercentage\":\"2\",\"x.com.samsung.da.supportedProgress\":[\"None\",\"Wash\",\"Rinse\",\"Spin\",\"Finish\"],\"x.com.samsung.da.progress\":\"Wash\",\"rt\":[\"x.com.samsung.da.operation\"]}}"
        },
"washerRinseCycles": {
            "value": "3"
        },
        "switch": {
            "value": "on"
        },

, если я использую в моем script

local switch = item.json.main.switch.value

Я получил или выключил va lua, и я могу использовать его для отображения состояния стиральной машины.

Я пытаюсь выяснить, как получить «data» значение в моем скрипте, есть еще элементы с точками и обратными символами:

local remainingTime = rt.data.value.payload['x.com.samsung.da.remainingTime'] 

или

local remainingTime = rt.data.value['\payload']['\x.com.samsung.da.remainingTime']

я попробовал еще несколько опций с 'или //, "" но всегда имеет нулевое значение.

Может кто-нибудь объяснить мне, как получить:

\ "x.com.samsung.da.remainingTime \": \ "01: 34: 00 \" \ "x.com.samsung .da.progressPercentage \ ": \" 2 \ ",

Все", \, x., ar сбивают меня с толку

Ниже приведен мой скрипт для проверки, где я только оставил Json log (Dzvents Lua Based) я получаю сообщение об ошибке:

dzVents / generate_scripts / Samsung_v3. lua: 53: попытка индексировать нулевое значение (глобальное 'json') я не делаю Вы можете понять, как использовать / настроить мой код для декодирования строки.

local json = require"json"  -- the JSON library
local outer = json.decode(your_JSON_string)
local rt = outer.main
local inner = json.decode(rt.data.value)
local remainingTime = inner.payload['x.com.samsung.da.remainingTime']

local API = 'API'
local Device = 'Device'


local LOGGING = true

--Define dz Switches
local WM_STATUS =  'WM Status'  --Domoitcz virtual switch ON/Off state  Washer


return 
{
    on = 
    {
        timer = 
        {
            'every 1 minutes', -- just an example to trigger the request
        },

        httpResponses = 
        {
            'trigger', -- must match with the callback passed to the openURL command
        },
    },

    logging = 
    { 
        level = domoticz.LOG_DEBUG ,
    }, 

    execute = function(dz, item)

        local wm_status = dz.devices(WM_STATUS)

        if item.isTimer then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
                headers = { ['Authorization'] = 'Bearer '.. API },
                method = 'GET',
                callback = 'trigger', -- see httpResponses above.

            })
        end

        if (item.isHTTPResponse) then
            if item.ok then
                if (item.isJSON) then


                   rt = item.json.main
            --      outer = json.decode'{"payload":{"x.com.samsung.da.state":"Run","x.com.samsung.da.delayEndTime":"00:00:00","x.com.samsung.da.remainingTime":"00:40:00","if":["oic.if.baseline","oic.if.a"],"x.com.samsung.da.progressPercentage":"81","x.com.samsung.da.supportedProgress":["None","Weightsensing","Wash","Rinse","Spin","Finish"],"x.com.samsung.da.progress":"Rinse","rt":["x.com.samsung.da.operation"]}}
                inner = json.decode(rt.data.value)
            --        local remainingTime = inner.payload['x.com.samsung.da.remainingTime']


                        dz.utils.dumpTable(rt) -- this will show how the table is structured
            --          dz.utils.dumpTable(inner)

                        local washerSpinLevel = rt.washerSpinLevel.value
            --       local remainingTime = inner.payload['x.com.samsung.da.remainingTime']




                        dz.log('Debuggg washerSpinLevel:' ..  washerSpinLevel, dz.LOG_DEBUG)
                     dz.log('Debuggg remainingTime:' ..  remainingTime, dz.LOG_DEBUG)

            --          dz.log('Resterende tijd:' .. remainingTime, dz.LOG_INFO)
            --          dz.log(dz.utils.fromJSON(item.data))


                  --  end
                elseif LOGGING == true then
                    dz.log('There was a problem handling the request', dz.LOG_ERROR)
                    dz.log(item, dz.LOG_ERROR)
                end
            end
        end
end
}


1 Ответ

0 голосов
/ 24 февраля 2020

Это странная конструкция: сериализованная JSON внутри обычного JSON.
Это означает, что вам придется дважды вызывать десериализацию:

local json = require"json"  -- the JSON library
local outer = json.decode(your_JSON_string)
local rt = outer.main
local inner = json.decode(rt.data.value)
local remainingTime = inner.payload['x.com.samsung.da.remainingTime']
...