python - Change JSON data received
问题描述
I am sending json file to my device over a MQTT broker.
The Python script to send the json data is
def send_data():
print("Inside Send data function")
jsonFile = open("dataFile.json", "r") # Open the JSON file for reading
data = json.load(jsonFile2) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
data_out = json.dumps(data)
print(data_out)
client.publish(topic2, data_out, 1, True) #Publish on topic on MQTT broker
The Output of this segment of script is
In send video AD function
{"link": "www.youtube.com", "link_id": "ad_1234"}
The JSON file to be send
{"link": "www.google.com", "link_id": "id_1234"}
_______________________________________________________________________________
The Python script to receive JSON data
def receive_data():
log.debug("Subscribing to topic")
ret = client.subscribe(topic, qos=1)
logging.info("Subscribed return = " + str(ret))
with open('file.json', 'w') as outfile:
json.dump(data, outfile)
statusFile = open('file.json', 'r')
status = json.load(statusFile)
statusFile.close()
The output of the File.json is
"{\"link\": \"www.youtube.com\", \"link_id\": \"ad_1234\"}"
I don't know why am I receiving in this format with extra "" and /. I want to receive my data in the same way as I am sending. How to do this?
解决方案
You're receiving a JSON-encoded string. JSON is a specification of how to turn certain kinds of objects into strings or byte sequences. If you want to turn a JSON-encoded string back into an object, use json.loads
on it:
>>> import json
>>> json.loads("{\"link\": \"www.youtube.com\", \"link_id\": \"ad_1234\"}")
{"link": "www.youtube.com", "link_id": "ad_1234"}
推荐阅读
- ios - 音乐信息显示在命令中心但不显示锁定屏幕
- amazon-web-services - ClientError:使用地面实况图像的 AWS object_detection_augmented_manifest_training 未指定训练通道
- mysql - 如何在没有通用“GROUP BY”元素的情况下组合来自 2 个查询的结果
- php - PHP 图像调整大小和展开占位符(透明)
- twitter-bootstrap - XPages 中的 bootstrapValidator
- android - 如何清理这些复杂的按钮?
- assembly - NASM 中的 FSTP 指令不会写入内存
- python - 如果我有完整的 url,如何使用函数 socket.gethostbyname 获取 IP 地址?
- java - 如何编写 REST API 并向使用现有 Web 应用程序的 REST API 的 android 用户提供身份验证?
- java - 如何在嵌套的 for 循环完成后运行 if 语句?