【问题标题】:How do I print out json data [closed]如何打印出 json 数据 [关闭]
【发布时间】:2021-03-22 16:14:42
【问题描述】:

我有一个如下所示的 JSON 文件:

{
   "data":{
      "uuid":"123",
      "name":"TestData",
      "alias":null,
      "created_at":"2021-03-17T11:57:29.000000Z",
      "updated_at":"2021-03-17T12:02:16.000000Z",
      "inactive_at":null,
      "default_language":"en",
      "questions":[
         {
            "id":2,
            "name":"application_process_rate",
            "type":"rating",
            "option_count":null,
            "option_max_choices":null,
            "custom":true,
            "order":0,
            "show_extra_comment":false,
            "comment_triggers":null
         },
         {
            "id":3,
            "name":"update_rate",
            "type":"rating",
            "option_count":null,
            "option_max_choices":null,
            "custom":false,
            "order":1,
            "show_extra_comment":false,
            "comment_triggers":null
         },
         {
            "id":204,
            "name":"process_feedbackQ119",
            "type":"rating",
            "option_count":null,
            "option_max_choices":null,
            "custom":false,
            "order":2,
            "show_extra_comment":false,
            "comment_triggers":null
         },
         {
            "id":44,
            "name":"process_overallsatisfaction",
            "type":"rating",
            "option_count":null,
            "option_max_choices":null,
            "custom":true,
            "order":3,
            "show_extra_comment":false,
            "comment_triggers":null
         }
      ]
   }
}

我已尝试在文件上使用 fetch,然后使用 response.json()。它给了我错误

Uncaught (in promise) SyntaxError: Unexpected token

我如何使用 javascript + react 来获取数据并将其打印在列表中?

【问题讨论】:

  • 发生错误的原因是因为您将 HTML 解析为 JSON,错误状态的第一个字符为 <。尝试获取所获取页面的正文
  • 您的 JSON 以“
  • 当您尝试获取文件并尝试将生成的 html 响应解析为 JSON 时,您很可能会收到 404(因此开始 <)。发布您的文件夹层次结构和执行提取的代码。

标签: javascript json reactjs


【解决方案1】:

读取 JSON 文件的最简单方法是使用它。

const json = require('./data.json')

这将读取数据并将其解析为 JavaScript 对象。 然后你可以随意迭代json.data.questions

【讨论】:

    【解决方案2】:

    Content-TypeAccept 标头设置为application/json

    fetch('file.json', {
      headers : { 
      'Content-Type': 'application/json',
      'Accept': 'application/json'
      }
    })
    .then(response => response.json())
    .then(jsonResponse => {
      jsonResponse.data.questions.forEach(q => console.log(q.name))
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多