通过密钥检索json数据

时间:2020-03-09 15:40:57

标签: javascript arrays json fetch

  const username = 'merMan';

  fetch("./datz.json")
    .then(response => response.text())
    .then((response) => {
        console.log(response);

    })

我的数据response如下所示,仍然很难获得简单的用户专用数据。我的response数据输出如下。我尝试使用find,但始终返回find不是函数,response[username]也不起作用。

[{"mermAn":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"catWoman":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"Riddler":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"}}]

2 个答案:

答案 0 :(得分:2)

您需要在response.text()之后解析响应,例如:

fetch("./datz.json")
    .then(response => response.text())
    .then((response) => {
        try {
          const parsedArray = JSON.parse(response);

          console.log(parsedArray);
        } catch (error) {
          // response could not be parsed
        }
    })

答案 1 :(得分:2)

使用.json()代替.text()

const username = 'merMan';

fetch("./datz.json")
  .then(response => response.json())
  .then((users) => {
      console.log(users.find(x => typeof x[username] !== "undefined"));
  })