在 Python 中通过 json 格式发送脚本文件

sending script files through json format in Python

我正在研究 IMB IOT application.It 基本上允许以 json 格式从一个设备向另一个设备发送命令或数据。我开发了 python 脚本,它从一个系统发送一个字符串并在另一个系统上接收。而且效果很好。现在我想处理脚本文件来代替字符串。但问题是 IBM IOT 仅支持 json 格式来转储有效负载。有什么方法可以将文件转换为 json 格式?

   i wrote a script which tries converting files to json format, doesn't work that perfect ! is there any other way to do that?

将脚本文件转换为 json

的代码

code output of code

Is there any way to make it work better?

这里是尝试通过 json 格式将文件发送到另一个系统的代码

act =input("Enter the key->")
file_path = input("\nPlease enter the file path->")
payload1 ={"computer1" : act}
update_file= open(file_path,'rb')
payload ={}
payload['context'] = base64.b64decode( update_file.read())
client.publishEvent("status",json,payload1,payload)

print(act)

print("command sent")
time.sleep(2)

另一台电脑

 def commandcallback(event):
   filename = payload['recieved_one]
   filedata = base64.base64decode(payload['context'])
   update_file =open(filename,'wb')
   update_file.write(filedata)
   update_file.close()

您可以实施自定义消息编解码器,以您选择的任何方式传输文件内容。

请参阅涵盖自定义消息格式使用的文档主题。 https://ibm-watson-iot.github.io/iot-python/custommsg/ ... 请记住,这些文档是针对待定的 1.0 版本(wiotp-sdk 而不是 ibmiotf),但是这方面它在 [= 的 0.4 版本中的工作原理几乎相同11=].

这取决于你想从中得到什么我建议如何处理这个:

您只对简单的文本文件感兴趣吗?

您可以编写一个简单的编解码器,以 utf-8(或您选择的任何编码)格式将数据作为简单字符串发送,为格式字符串注册编解码器 utf8 并将其用作格式发送事件时的字符串,以便客户端知道这是您想要编码和决定消息有效负载的方式,这意味着您在应用程序上获得的 event.data 将是文件内容的 UTF-8 编码字符串。

你想用它来传输任何文件,而不考虑内容类型吗?

您可以编写编解码器,使其仅传递适合直接写入处理事件的应用程序上的文件的原始字节数组(例如,使用格式字符串 raw),在本例中为 event.data 会给你一个字节数组,可以很容易地用于在接收应用程序上写入文件。

希望这能让您对使用客户端库中内置的自定义消息支持可以做什么有所了解。当我周一回到办公室时,我会看看将这些作为示例添加到 repo 中。