Search code examples
jsonreact-nativefetch

How to extract key and value from json in fetch method in React Native?


I'm new in React Native. I would like to extract a value from json with fetch to do a simple test to begin. But I don't understand, how to select a particular key from Json. Always, I have undefined return. I tried to modify my code with this post but it doesn't work. I tried to parse before but he didn't want because it's already an object.

This is my code:

checkLogin = () => {

    const { name } = this.state;
    const { surname } = this.state;

    fetch('https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=' + name + '%20' + surname, {
        method: 'GET',
    }).then((response) => response.json())
        .then((responseJson) => {
            if (responseJson.ind == 'Individu non trouv\u00e9 !') {
                alert("Id incorrect")
            }
            else {
                alert("Id correct");
            }
            alert(JSON.stringify(responseJson.ind))

        }).catch((error) => {
            console.error(error);
        });

}

This is my JSON format:

[{"iuf":"1366701","ind":"LEBRUN L\u00e9o (2000) H FRA - CN BEAUPREAU","sex":"#1e90ff","clb":"CN BEAUPREAU"}]

I know my request work because when I run this code alert(JSON.stringify(responseJson)).It return the entire json. So I don't know, how to resolve the undefined return.

Regards


Solution

  • Your json is an array, you either need to loop through it if there is multiple items inside, or just use responseJson[0] to read it. So if you want to read your json, your code would look like this :

    const checkLogin = () => {
        const { name } = this.state;
        const { surname } = this.state;
    
        fetch(
          "https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
            name +
            "%20" +
            surname,
          {
            method: "GET"
          }
        )
          .then(response => response.json())
          .then(responseJson => {
            // Since you have only one object inside your json, you can read the first item with 'responseJson[0]'.
            if (responseJson[0].ind == "Individu non trouv\u00e9 !") {
              alert("Id incorrect");
            } else {
              alert("Id correct");
            }
            alert(JSON.stringify(responseJson[0].ind));
    
            // If you have multiple elements inside your responseJson, 
            // then here is a loop example :
    
            // responseJson.forEach(item => {
            //   console.log('item ind = ', item.ind);
            // });
          })
          .catch(error => {
            console.error(error);
          });
      };