【问题标题】:Read a JSON file using JavaScript使用 JavaScript 读取 JSON 文件
【发布时间】:2016-07-11 07:39:26
【问题描述】:

我正在使用 Django 框架进行 Web 开发。我想读取 JSON 文件并将其内容打印到网页上。

这是我的脚本:

<script type="text/javascript"
        src = "file:///home/pragna/myproject/myapp/templates/myapp/segment2.json">
</script>

<script>
    var mydata = JSON.parse(jsonstr);
    alert(mydata[0].text);
</script>  

我已按以下格式存储我的 JSON 文件:

jsonstr = [
     {
         "text": "this is the text",
         "name" : "thisisme"
     },

     {
         "text": "some more text",
         "name" :"thisisaname"
     }
]

当我运行服务器时,网页请求文件时没有404错误,但是也没有警报。

【问题讨论】:

  • 文件不是正确的 json。`jsonstr` 需要用双引号括起来,所有的东西都应该用 `{}' 包裹起来,即第一个是 {,最后一个是 }。但这可能并不重要,因为据我所知,它被视为更像一个数组。

标签: json django file-handling


【解决方案1】:

我运行服务器时,网页没有出现404错误 请求文件

您的意思是服务器中没有 404 错误。浏览器控制台仍会显示 404 错误,因为您使用的是 file:/// url 来加载 JSON。

<script type="text/javascript", src ="file:///home/pragna/myproject/myapp/templates/myapp/segment2.json">    </script>

这应该是 http://、https:// 或像 /segment2.json 这样的相对 url

【讨论】:

    【解决方案2】:

    无需解析

    alert('{{ jsonstr.0.text }}');
    

    【讨论】:

    • 这不返回一个显示{{ jsonstr.0.text }} 的字符串吗?因为它在报价中
    【解决方案3】:

    您将得到 404,因为您正尝试访问本地计算机中带有 file:/// 前缀的文件,这是您的真实演示:

    <script type="text/javascript" src ="http://www.mocky.io/v2/5797d7190f00005c0ef0809e"></script>
    
    <script type="text/javascript">
     alert(jsonstr[0].text);
    </script>
    

    【讨论】:

      【解决方案4】:

      您不需要解析内容,因为它已经是 JSON。

      试试这个:

        <script type="text/javascript" src ="file:///home/pragna/myproject/myapp/templates/myapp/segment2.json"></script>
          <script>
              alert(jsonstr[0].text);
          </script>  
      

      应该可以。

      也就是说,我认为在这种情况下,XmlHttpRequest 是更好的选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-15
        • 2013-03-20
        • 2019-09-14
        • 2016-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        相关资源
        最近更新 更多