首页 > 解决方案 > 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?

标签: pythonjson

解决方案


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"}

推荐阅读