节点从 url 中获取 json

node fetching json from url

我正在尝试在 Nodejs 中获取并解析下面返回的 JSON。问题似乎是节点代码试图解析包含换行符的 JSON 字符串,但我不确定如何避免这种情况,以及为什么 fetch 在 chrome devtools 中工作。我猜问题是我对 https 请求的简单了解,所以如果有人能解释出问题所在,我将不胜感激。

const url = "https://beta.charitycommission.gov.uk/umbraco/api/charityApi/getSearchResults?searchText=&pageNumber=1&contextId=1126&onlyShow=&&&&&&&"

我可以在域上打开 chrome devtools 成功 运行 这个。此外,JSON 似乎会自动解析为一个对象,这是我没想到的。

fetch(url).then(res => res.json()).then(json => console.log(json.pageItems))

我在节点中尝试了以下方法,但 none 有效。

const fetch = require("node-fetch");
await fetch(url).then(res => res.json()); // Unexpected token  in JSON at position 0

const rp = require('request-promise-native');
const json = await rp({uri: url}) // returns JSON string with newline characters
JSON.parse(json) // Unexpected token  in JSON at position 0

尝试使用默认 fetch:

const json = await fetch(url).then(res => res.json())

res.json() 解析 JSON 数据和 return 对象。使用await将return数据放入变量json.

问题是您的 JSON 文件是以 UTF-8 BOM 格式保存的。

什么意思?

您的文件以所谓的字节顺序标记字符 U+FEFF (Zero Width No-break Space) 开头。

那是不可见的(宽度为零),但仍然存在,JSON 解释器无法解析它。

如何解决?

  1. 保存没有BOM的JSON数据,或者
  2. 先用res.text()再用JSON.parse(text.slice(1))去掉前导:

    fetch(url)
    .then(res => res.text())
    .then(text => JSON.parse(text.slice(1)))
    .then(json => console.log(json.pageItems))
    

为什么在Chrome中有效?

Chrome 自动从任何 fetched/downloaded 文件中删除 BOM 字符,以避免类似问题。