更改收到的JSON数据

时间:2018-08-04 07:21:21

标签: python json

我正在通过MQTT代理将json文件发送到我的设备。

用于发送json数据的Python脚本是

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

此段脚本的输出为

In send video AD function
{"link": "www.youtube.com", "link_id": "ad_1234"}

要发送的JSON文件

{"link": "www.google.com", "link_id": "id_1234"}

_______________________________________________________________________________

用于接收JSON数据的Python脚本

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()

File.json的输出为

"{\"link\": \"www.youtube.com\", \"link_id\": \"ad_1234\"}"

我不知道为什么我会收到这种带有额外的“”和/的格式。我想以与发送相同的方式接收数据。该怎么做?

2 个答案:

答案 0 :(得分:4)

您将收到JSON编码的字符串。 JSON是有关如何将某些类型的对象转换为字符串或字节序列的规范。如果您想将JSON编码的字符串转换回对象,请在其上使用json.loads

>>> import json
>>> json.loads("{\"link\": \"www.youtube.com\", \"link_id\": \"ad_1234\"}")
{"link": "www.youtube.com", "link_id": "ad_1234"}

答案 1 :(得分:1)

python 3.6+很漂亮,以下代码要求它:

import json
from pathlib import Path
def send_data():
    print("Inside Send data function")
    fname = "dataFile.json"  # the JSON file
    """
    # just read the file, no need to json loads and dumps
    data = json.loads(Path(fname).read_text())  # Read file and loads
    data_out = json.dumps(data)
    """
    data_out = Path(fname).read_text()
    print(data_out)
    client.publish(topic2, data_out, 1, True)    #Publish on topic on MQTT broker

def receive_data():    
    log.debug("Subscribing to topic")
    ret = client.subscribe(topic, qos=1)
    logging.info(f"Subscribed return = {ret}")
    fname = "file.json"
    Path(fname).write_text(data)
    status = json.loads(data)