【问题标题】:Python: How to get JSON object from a UDP received packetPython:如何从 UDP 接收的数据包中获取 JSON 对象
【发布时间】:2017-02-22 16:48:30
【问题描述】:

我正在使用 UDP 数据包通过网络发送此温度和湿度读数,但是。由于 UDP 只接受 1 个参数,我将它们放入一个 JSON 对象,然后是一个字符串。当我收到数据包时,我似乎无法从收到的数据包中取出我想要的值

#!/usr/bin/python
import sys
import time
import socket
import Adafruit_DHT
import json

UDP_IP = "192.168.42.18"
PORT = 5001

my_ip = socket.gethostbyname(socket.getfqdn())

print "server has started",


while True:
   humidity, temperature = Adafruit_DHT.read_retry(11, 4)#initialising DHT11 temp sensor

   print 'Temp: {0:0.1f} C  Humidity: {1:0.1f} %'.format(temperature, humidity)
   print time.asctime()#printing to the terminal values

   json_string = {}
   json_string ['details'] = {'ip': my_ip, 'temp':temperature,  'humidity':humidity}

   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#initalising socket and UDP connection
   Message = str(json_string)
   print 'Message sent:= ', Message

   sock.sendto(Message,(UDP_IP, PORT))
   print "SENT to:-", UDP_IP, PORT, "From", my_ip

   time.sleep(3)#delay

接收代码

import socket
import time
import json

port = 5001

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

sock.bind(("", port))

print "server started"

while True:
   recieved = sock.recvfrom(1024)
   print type(recieved)
   print recieved[0]
   print time.asctime()#bytes object


   json_obj = json.dumps(recieved)

   print type(json_obj)

   print json_obj ['details']['temp']

#json_converted = json.loads(json_obj)
#print type(json_converted)

#json_string = map(str,(json_converted))

   print "converted Json:- "
#print json_string['details']['temp']
   print "Temperature in Celsuius"

我不断收到格式错误的错误。什么是正确的方法。

server started
<type 'tuple'>
{'details': {'ip': '127.0.1.1', 'temp': 20.0, 'humidity': 49.0}}
Wed Feb 22 16:27:06 2017
<type 'str'>
Traceback (most recent call last):
File "/Users/Faiz/Desktop/Rpi_Sensors_UDP/sensor_listenerUDP.py", line 24, in     <module>
 print json_obj ['details']['temp']
 TypeError: string indices must be integers, not str

Process finished with exit code 1

【问题讨论】:

    标签: python json sockets networking


    【解决方案1】:

    处使用 json.loads
    json_obj = json.loads(recieved[0])
    

    而不是

    json_obj = json.dumps(recieved)
    

    json.loads 会将你收到的字符串转换为dict,然后你就可以得到你的数据了

    喜欢这个

    import socket
    import time
    import json
    
    port = 5001
    
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    
    sock.bind(("", port))
    
    print "server started"
    
    while True:
       recieved = sock.recvfrom(1024)
       print type(recieved)
       print recieved[0]
       print time.asctime()#bytes object
    
    
       json_obj = json.loads(recieved[0])
    
       print type(json_obj)
    
       print json_obj.get('details').get('temp') 
    
    #json_converted = json.loads(json_obj)
    #print type(json_converted)
    
    #json_string = map(str,(json_converted))
    
       print "converted Json:- "
    #print json_string['details']['temp']
       print "Temperature in Celsuius"
    

    【讨论】:

    • ValueError: Expecting property name: line 1 column 2 (char 1) 是我得到的错误。它说它在第 19 行
    【解决方案2】:

    如下在接收中使用 json.loads(recieved[0]) 代替,并使用 json.dump 从 JSon 创建一个字符串

    #!/usr/bin/python
    import sys
    import time
    import socket
    import Adafruit_DHT
    import json
    
    UDP_IP = "192.168.43.113"
    PORT = 5001
    
    my_ip = socket.gethostbyname(socket.getfqdn())
    
    print "server has started",
    
    while True:
        humidity, temperature = Adafruit_DHT.read_retry(11, 4)#initialising DHT11 temp sensor
    
        print 'Temp: {0:0.1f} C  Humidity: {1:0.1f} %'.format(temperature, humidity)
        print time.asctime()#printing to the terminal values
    
    
        json_string = json.dumps({"ip": my_ip, "temp": temperature, "humidity": humidity})
        #here put the created JSON into a string using json.dumps also checked the JSON string for validity using jsonlint.
    
    
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#initalising socket and UDP connection
    
        Message = json_string
        print 'Message sent:= ', Message
    
        sock.sendto(Message,(UDP_IP, PORT))
        print "SENT to:-", UDP_IP, PORT, "From", my_ip
    
        time.sleep(3)#delay 5 mins
    

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多