Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文本文件加载json_Python_Json - Fatal编程技术网

Python 从文本文件加载json

Python 从文本文件加载json,python,json,Python,Json,我试图运行此代码,但它会产生错误 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.

我试图运行此代码,但它会产生错误

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())
它表明


我是编程新手,不知道问题出在哪里。

您似乎试图逐行解析json文件,但json对象可能(通常)跨越多行。您需要完整的文件才能解析它:

 with open('data.txt') as o1:
      data = json.loads(o1.read()) # read ALL the file and parse. no loops
 print(data)

我使用以下方法解决了我的问题:

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())

它只有在从crontab启动时才会抛出错误吗?不,每当我运行这个脚本时,它都会抛出这个错误我很抱歉,我认为这个问题的标题在启动时不正确?可能网络还没有启动?顺便说一句,向我们展示这个脚本的输出。我尝试了这个代码,但它再次抛出一个错误:值错误:额外数据:@Aaron.0你能在任何外部json阅读器中打开
'Data.txt'
?看起来这个文件“不是纯粹的”json(?)它的json很好,当“data.txt”中只有一个数据时它运行良好,但当有超过个数据时会抛出错误that@Aaron.0谁写
data.txt
?为什么里面有几个“json数据”?
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())