Lieutenant Dan
Lieutenant Dan

Reputation: 8294

retrieving json data by a key

  const username = 'merMan';

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

    })

my data response looks like below, still having a difficult time simply getting a user specific data. My response data outputs like below. I have tried using find, but always returns find is not a function, response[username] does not work either.

[{"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"}}]

Upvotes: 0

Views: 65

Answers (2)

Andreas
Andreas

Reputation: 21911

Use .json() instead of .text()

const username = 'merMan';

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

Upvotes: 2

giankotarola
giankotarola

Reputation: 775

You need to parse the response after response.text(), like:

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
        }
    })

Upvotes: 2

Related Questions