Javascript 如何打印json数据
我有一个JSON文件,如下所示:Javascript 如何打印json数据,javascript,json,reactjs,Javascript,Json,Reactjs,我有一个JSON文件,如下所示: { "data":{ "uuid":"123", "name":"TestData", "alias":null, "created_at":"2021-03-17T11:57:29.000000Z", "updated_at&q
{
"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()
。它给了我错误
未捕获(承诺中)语法错误:JSON中的意外标记<位于
位置0
如何使用javascript+react获取数据并将其打印在列表中?读取JSON文件的最简单方法是需要它
const json = require('./data.json')
这将读取数据并将其解析为JavaScript对象。
然后,您可以根据需要迭代
json.data.questions
。使用Content-Type
和Accept
标题设置为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))
});
出现错误的原因是,您正在将HTML解析为JSON,第一个字符是
,您的JSON以“您在尝试获取文件并尝试将生成的HTML响应解析为JSON时,很可能会得到404
(因此开始