如何将 text/html charset=UTF-8 响应转换为 json

问题描述 投票:0回答:1

我正在调用一个返回内容类型为 text/html charset=UTF-8 的 API。当我记录它时,结果看起来与 json 完全一样。但是当我记录 typeof 时,它说它是一个字符串。当我尝试访问它的属性时,我得到一个未定义的值。

首先,我尝试将其转换为 JSON: const requestData = 函数(页码) {
返回新的 Promise((解决, 拒绝) => { 常量 url =

http://www.website.com/...
;

request(url, (error, response, body) => {
  if (error) return reject(error)
  if (response.statusCode !== 200) return reject(response)
  console.log('Body: ', JSON.parse(body))
  resolve(body)
})

}) }

这会引发错误:

SyntaxError: Unexpected token m in JSON at position 1

我还尝试在解析正文之前对其进行转义:

fixedstring = decodeURIComponent(escape(body))
console.log('keys: ', JSON.parse(fixedstring))

我也遇到同样的错误。

如前所述,当我记录正文时,它看起来与 JSON 相同:

...
console.log('body: ', body);
...
// Result printed to console:

    body:  {metadata:{ count:"1200", totalpages:400}, data:[{
      "city" : "Clearwater",
      "state" : "FL",
      "zip" : "33760",
    },{ 
    ...

如何将其转换为 JSON?

javascript json request
1个回答
0
投票

就我而言,我使用了

await response.text()
而不是
await response.json()

© www.soinside.com 2019 - 2024. All rights reserved.