JSON相机点结构TypeError:期望的字符串或缓冲区

时间:2018-06-18 12:41:28

标签: python json typeerror ros calibration

目前我正致力于从相机输出中收集点数。我有4台相机。他们都需要以类似于

的结构发布到文件中
{
'camera1':data.IP,
'point:data'.point,

'camera2':data.IP,
'point:data'.point,

'camera3':data.IP,
'point:data'.point,

'camera4':data.IP,
'point:data'.point,
...........
.........
...........
}

如果相机看到一个点 - 它应该将其张贴在一个文件中,否则它不会发布任何内容并且它的IP和点不会出现。只要我们看到积分,我们就会将其转储到文件中。我现在这样做,它看起来像是不同括号中每个摄像机的单独片段。

我正在尝试创建一个结构,将我的数据加载到此结构中并对其进行规范化。但是我收到了一个错误:

data = json.loads(CAM) TypeError: expected string or buffer

任何机会,你知道如何解决这个问题吗?

我附上了一个真实的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import rospy
import json
from std_msgs.msg import String
from pixart.msg import raw_point
from pandas.io.json import json_normalize
from pandas import DataFrame

def Load_file(data):
     with open('/home/ragesh/catkin_ws/src/pixart/src/data.json', 'a') as f:
        json.dump(data, f, indent=5)  


def callback(data):
    print data
    CAM = [{'camera_id': data.camera_id,
            'point':[
                {'x':data.x},
                {'y':data.y}],
            'secs': data.stamp.secs,
            'nsecs': data.stamp.nsecs}]
   # CAM = json_normalize(CAM, 'camera_id', 'x', 'y', 'secs', 'nsecs')
    data = json.loads(CAM)
    data = json_normalize(data)

    Load_file(data)




def subscriber():
    rospy.init_node('data_store', anonymous=True)
    rospy.Subscriber('/pixart_raw', raw_point, callback)
    while not rospy.is_shutdown():

        rospy.sleep(10)


if __name__ == '__main__':
    subscriber()

1 个答案:

答案 0 :(得分:0)

这不是有效的JSON,因为您的节点是重复的,

你可以用两种不同的方式做到:

{
'camera1':data.IP,
'point1':data.point,

'camera2':data.IP,
'point2':data.point,

'camera3':data.IP,
'point3':data.point,

'camera4':data.IP,
'point4':data.point,
...........
.........
...........
}

[  {"camera":"data.IP","point":"data.point"},  {"camera":"data.IP","point":"data.point"},  {"camera":"data.IP","point":"data.point"},   {"camera":"data.IP","point":"data.point"}  ]

如何向此JSON添加元素的示例:

a=[  {"camera":"data.IP","point":"data.point"},  {"camera":"data.IP","point":"data.point"}] #declare my dictionary
print (a) #print my dictionary
a.append({"test":1}) #add element to dictionary
print (a) #print again the dictionary that will contain my new element

其他示例(如果数据结构不同,则可能会有所不同):

def callback(data):
    #I create many list for each variable
    ids=[]
    x=[]
    y=[]
    secs=[]
    nsecs=[]
    #I introduce in my lists all the values
    ids.append(data.camera_id)
    x.append(data.x)
    y.append(data.y)
    secs.append(data.stamp.secs)
    nsecs.append(data.stamp.nsecs)
    CAM=[]
    #I create a loop for each camera id and for each element I create a new line regarding the specific camera in CAM
    i=0
    while i<len(ids):
        CAM.append({'camera_id': ids[i],'point':[{'x':x[i]},{'y':y[i]}],'secs': secs[i],'nsecs': nsecs[i]})
        i+=1
    data = json.loads(CAM)
    data = json_normalize(data)

    Load_file(data)