简体   繁体   English

append数据如何到python中的json文件?

[英]How to append data to json file in python?

I have a json file with these data inside:我有一个 json 文件,里面有这些数据:

[
  {
    "t1": 62.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 62.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 63.000000,
    "t2": 26.200001,
    "Ir": 100
  }
]

Then on my python code, i read it with these command:然后在我的 python 代码上,我用这些命令读取它:

with open("data.json", 'r+') as file:
    old_data_list = json.load(file)

The type of old_data_list is <class 'list'> old_data_list 的类型是<class 'list'>

So I want to append some data to this list.所以我想 append 一些数据到这个列表。 I receive the data from a ESP32 and then a read it with this command:我从 ESP32 接收数据,然后使用以下命令读取它:

data = message.payload.decode('utf-8') # turn bytes to string

When i try to append the data to the json file, that's what i get:当我尝试将 append 数据写入 json 文件时,这就是我得到的:

[
  {
    "t1": 62.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 62.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 63.000000,
    "t2": 26.200001,
    "Ir": 100
  },"{"t1":64.000000,"t2":25.799999,"Ir":100}"
]

But what i want is:但我想要的是:

[
  {
    "t1": 62.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 62.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 63.000000,
    "t2": 26.200001,
    "Ir": 100
  },
  {
    "t1": 64.000000,
    "t2": 25.799999,
    "Ir": 100
  },
]

Python does the right thing as data is a string, not a dictionary. Python 做了正确的事情,因为data是一个字符串,而不是字典。 Try:尝试:

data = json.loads(message.payload.decode('utf-8'))

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

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