简体   繁体   English

Python dict 通过 JSON 和 Rails Action Cable Web 套接字转换为 Ruby 哈希

[英]Python dict to Ruby hash through JSON and Rails Action Cable web socket

I am having a hard time passing information properly from a python script to a rails app through web sockets (using Action Cable).我很难通过网络套接字(使用 Action Cable)将信息从 python 脚本正确传递到 rails 应用程序。

I want to use input information in a python dictionary like this :我想在这样的 python 字典中使用输入信息:

message = {
    'command':"subscribe",
    'identifier':{
            'channel': 'RaspChannel',
            'rasp_local_id': '1'
        }
    }

It should then be converted into JSON, go through a web socket set by Action Cable, then parsed into a ruby hash on the server side.然后应该将其转换为 JSON,通过 Action Cable 设置的 Web 套接字,然后在服务器端解析为 ruby​​ 哈希。

For some reason, I only made it work by sending a plain string through the socket :出于某种原因,我只是通过套接字发送一个普通字符串来使它工作:

'{"command":"subscribe","identifier":"{\\"channel\\":\\"RaspChannel\\", \\"rasp_local_id\\": \\"1\\"}"}'

But I could not make it work by sending json.dumps(message) even though it returned something that looked pretty good to me :但是我无法通过发送json.dumps(message)使其工作,即使它返回了一些对我来说看起来不错的东西:

{"command": "subscribe", "identifier": {"channel": "RaspChannel", "rasp_local_id": "1"}}

I suppose action cable protocol uses the classic ruby JSON.parse method on the json string it receives as input, and for some reason, it always throws a parsing error, unless I use the plain string I mentioned above.我想动作电缆协议在它作为输入接收的 json 字符串上使用经典的 ruby JSON.parse方法,并且出于某种原因,它总是抛出解析错误,除非我使用我上面提到的纯字符串。

However, as I want to make the message more complicated, it would be better if I could make it work with actual Python dictionaries from the beginning.但是,因为我想让消息变得更复杂,所以如果我能从一开始就让它与实际的 Python 词典一起工作会更好。

Any idea on what I am missing ?知道我缺少什么吗?

After more research, it seems that the issue did not come from either JSON python encoding, ruby decoding, or me misusing any of these methods.经过更多研究,似乎问题不是来自 JSON python 编码、ruby 解码,也不是我滥用这些方法。

Actually, it would seem that the protocol used by actioncable when receiving messages does not exactly rely on a "classic" JSON, but uses "escaped JSON within the JSON" for the identifier实际上,actioncable 在接收消息时使用的协议似乎并不完全依赖于“经典”JSON,而是使用“JSON 中的转义 JSON”作为标识符

More on that on the rails github issue here https://github.com/rails/rails/issues/22675更多关于 rails github 问题的信息,请访问https://github.com/rails/rails/issues/22675

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM