【问题标题】:Parsing JSON With Requests library In Django在 Django 中使用请求库解析 JSON
【发布时间】:2019-09-02 12:46:06
【问题描述】:

我无法正确解析 json。我正在使用请求库进行解析。我在本地主机上获取了整个 json,但无法解析单个项目。

这是我的 json 网址中的 json 标头。

[{"id": 4, "company_name": "Ta..........oor guide. "}, {" id ": 5," company_n........is campaign. \ n "}]

我的views.py 文件

from django.shortcuts import render

def home(request):
    import requests
    import json
    api_request = requests.get('https://us-c..../content_all/json')

    try:
        api = json.loads(api_request.content)

    except Exception as e:
        api = "Error"

    return render(request, 'home.html', {'api':api})

这是我的home.html 文件

{% extends 'base.html' %}
{% block content %}

{{ api }}   

{% endblock %} 

当我在home.html 中仅尝试 api 时,它会显示整个 json,但是当我尝试此操作时

{{ api.company_name }}     #company_name is key in my json

一个空白页来了。你能帮帮我吗?

【问题讨论】:

    标签: json django python-3.x


    【解决方案1】:

    您的变量api 是一个字典列表,而不是直接的字典。

    所以要访问你可以做的其中一个字典的company_name

    {{ api.0.company_name }}      {% this is the first element of the list %}
    {{ api.1.company_name }}      {% this is the second element of the list %}
    

    或者迭代它们

    {% for elem in api %}
        {{ elem.company_name }}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      您的 JSON 似乎无效。 有 2 个左花括号 ({) 但只有 1 个右花括号 (}),因此数据解析应该会因此而失败。

      检查您获得的 JSON 是否确实是您应该获得的正确内容。也许源发送了错误的数据?还是您只是将其错误地复制粘贴到此处的问题中?

      【讨论】:

      • 我编辑了我的问题,更新了我在 url 中的 json 源文件。
      猜你喜欢
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 2018-10-27
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多