我正在尝试运行此代码,但它会产生错误。
import json
import requests
import pprint
data = []
with open('data.txt') as o1:
for line in o1:
data.append(json.loads(line))
print(data)
print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())
显示
Value Error: No json object could be Decoded
我是编程新手,无法弄清问题是什么。
答案 0 :(得分:1)
您似乎正在尝试逐行解析json文件,但json对象可能(通常是)跨越多行。您需要拥有整个文件才能解析它:
with open('data.txt') as o1:
data = json.loads(o1.read()) # read ALL the file and parse. no loops
print(data)
答案 1 :(得分:0)
我用这个解决了我的问题:
data =[]
with open('data.txt') as f:
for line in f:
data = json.loads(line)
print(data)
url = 'http://xyz.abcdfx.cn/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())