简体   繁体   English

Python:如何从 UDP 接收到的数据包中获取 JSON 对象

[英]Python: How to get JSON object from a UDP received packet

I am sending this temperature and humidity reading using UDP packets across the network but.我正在通过网络使用 UDP 数据包发送此温度和湿度读数。 As UDP only accepts 1 argument, i have put them into a JSON object then a string.由于 UDP 只接受 1 个参数,我将它们放入一个 JSON 对象中,然后放入一个字符串中。 When i receive the packet i cannot seem to get out the values i want from the received packet当我收到数据包时,我似乎无法从收到的数据包中获取我想要的值

#!/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

receiving code接收码

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"

I keep getting errors of the wrong format.我不断收到错误格式的错误。 What is the correct method.什么是正确的方法。

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

use json.loads at使用 json.loads 在

json_obj = json.loads(recieved[0])

instead of代替

json_obj = json.dumps(recieved)

json.loads will convert your received string to dict and then you can get your data json.loads 会将您收到的字符串转换为 dict,然后您就可以获取数据

like this像这样

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"

As Below in the recieve use json.loads(recieved[0]) instead and also create a string from the JSon using json.dump如下在接收中使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM