【问题标题】:Encoding error when trying to open json file from django app尝试从 django 应用程序打开 json 文件时出现编码错误
【发布时间】:2020-02-03 13:17:54
【问题描述】:

我在与我的应用程序相同的目录中有一个json 文件,我在其中保存了一些名称和密码。当用户单击按钮时,我试图检索这些数据并将其与他提供的输入进行比较。但是,我收到编码错误 JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我尝试添加errors='ignore' 并更改编码但没有成功。

我的登录功能打开json文件:

def login(name,password):
    with open('data.json', 'r', encoding='utf-8', errors='ignore') as f:
        try:
            data = json.loads(f.read())
            #data = json.load(f) didnt work also
            print(data)

        except ValueError:  # includes simplejson.decoder.JSONDecodeError
            print('Decoding JSON has failed')
            return False

        f.close()

这是在我的 django 应用程序中

def test(request):
    if request.method == 'POST':
        given_name = request.POST.get('name', None)
        given_password = request.POST.get('pass', None)
        # do something with user
        if login(given_name, given_password):
            about(request)
        else:
            test_home(request)
         ....

Json 文件:

{
    "names": [
        "test",
    ],
    "passwords": [
        "test",
    ]
}

【问题讨论】:

  • 这带来了另一个错误:TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper' 如果我使用 json.load(f) 则不会显示
  • 您的json 文件可能是空的,或者您使用了错误的路径打开它。
  • 你的“data.json”中有这些奇怪的字符吗? stackoverflow.com/questions/38883476/…
  • 它不是空的,它在同一个文件夹中,为什么路径会导致问题?
  • 查看您的json 内容,“名称”/“密码”列表中的字符串后面有逗号。 json 因此需要更多列表元素...尝试删除逗号,对我有用。

标签: python json django


【解决方案1】:

尝试修改我在评论中指出的 json 文件;

{
    "names": [
        "test"
    ],
    "passwords": [
        "test"
    ]
}

现在你应该得到

with open(file) as f:
    data = json.load(f)

data
Out[5]: {'names': ['test'], 'passwords': ['test']}

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 2016-04-20
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多