[英]Fetching local JSON object with React.js problem, Error: Unexpected token < in JSON at position 0
So i want to fetch from my local data.js file.所以我想从我的本地 data.js 文件中获取。 It looks like this:
它看起来像这样:
{
product_name: [
{'name': 'hello',
'lastName': 'hello'
}, {'name': 'hi',
'lastName': 'hi'}
]
}
Is this valid JSON?这是有效的 JSON 吗? My code that I'm fetching it with looks like this:
我正在获取它的代码如下所示:
fetch('./data.json')
.then(res=> res.json())
.then(text=> console.log(text))
After this, I get an error in my console.log.在此之后,我的 console.log 中出现错误。 Also when I go to the network tab and click on data.json It tells me that javascript needs to be enabled, what does that mean?
另外,当我 go 到网络选项卡并单击 data.json 它告诉我需要启用 javascript 时,这是什么意思? Thank you guys
感谢你们
I might be able to solve your answer.我也许能够解决你的答案。
You must remember to format the JSON so that it is readable by a user, if you are currently developing your program.如果您当前正在开发程序,您必须记住格式化 JSON 以便用户可以读取它。 In production mode, you can skip this step, but it is a good practice.
在生产模式下,您可以跳过此步骤,但这是一个很好的做法。
Next, The JSON you have does not seem to use quotes for keys.接下来,您拥有的 JSON 似乎没有使用引号作为键。 This is a must for JSON.
这是 JSON 必须的。 If you don't like the quotes, use json5 , JSON's friendlier brother.
如果您不喜欢引号,请使用 JSON 的友好兄弟json5 。
This explains about JSON with fetch
.这解释了 JSON 和
fetch
。
The Fetch API returns a response stream in the promise.
Fetch API 在 promise 中返回响应 stream。 The response stream is not JSON, so trying to call JSON.parse on it will fail.
响应 stream 不是 JSON,因此尝试调用 JSON.parse 将失败。 To correctly parse a JSON response, you'll need to use the response.json function.
要正确解析 JSON 响应,您需要使用 response.json function。 This returns a promise so you can continue the chain.
这将返回 promise,因此您可以继续该链。
I see that you have done it, but are forgetting the GET
method mentioned in the above post.我看到你已经做到了,但是忘记了上面帖子中提到的
GET
方法。 And, use return
keyword to pass the JSON to the next promise.并且,使用
return
关键字将 JSON 传递给下一个 promise。 So, your corrected JS code will be:因此,您更正的 JS 代码将是:
fetch('./data.json', { method: "GET" })
.then(res => return res.json())
.then(text => console.log(text))
I am not an expert in React, but these are some common things I can correct.我不是 React 方面的专家,但这些是我可以纠正的一些常见问题。
I do not really know why it says JavaScript needs to be enabled.我真的不知道为什么它说 JavaScript 需要启用。 Maybe go to your settings and enable JavaScript?
也许 go 到您的设置并启用 JavaScript? Or, if you use an ad-blocker, try disabling it once and see.
或者,如果您使用广告拦截器,请尝试禁用它一次并查看。
I think I have solved a part of your question.我想我已经解决了你的部分问题。 If this helped you, I would be very pleased.
如果这对您有所帮助,我将非常高兴。 Thanks!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.