Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.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 loads()可以将函数reslut(string)作为输入吗?_Python_Json - Fatal编程技术网

Python loads()可以将函数reslut(string)作为输入吗?

Python loads()可以将函数reslut(string)作为输入吗?,python,json,Python,Json,据我所知,json.loads()将字符串作为输入,所以我不知道下面的代码为什么不起作用 import json fileref = open("olympics.txt", "r").readline() # the output is str print(fileref) print(type(fileref)) d = json.loads(fileref) 错误: ExternalError: SyntaxError: Unexpected token N in JSON at po

据我所知,json.loads()将字符串作为输入,所以我不知道下面的代码为什么不起作用

import json
fileref = open("olympics.txt", "r").readline()  # the output is str
print(fileref)
print(type(fileref))
d = json.loads(fileref)
错误:

ExternalError: SyntaxError: Unexpected token N in JSON at position 0 on line 8

谢谢大家!

这是因为
fileref
不是语法上有效的JSON字符串。除非您知道文件的第一行应该是JSON对象,否则我假设整个文件都是JSON对象(这是常见的)。可以使用json.load函数读取文件

或者您可以将文件存储到字符串中,然后使用如下加载

content = ""
with open("file.txt","r") as f:
     for line in f:
         content += line
json.loads(content)

编辑:我不知道您的文件结构,我只是假设它是一个JSON文件(即它的所有JSON)。如果是这样的话,那么我所提到的将是准确的。否则,您看到的错误是因为正在解析的字符串不是有效的JSON。

打印(fileref)的结果是什么?我们需要源字符串来回答这个问题。它说第8行有一个问题,但它来自readline,这至少令人费解。我们希望看到
olympics.txt
文件。看起来里面没有正确的JSON文件。