Home > front end >  extract a field from a json file through a network request in react native
extract a field from a json file through a network request in react native

Time:08-24

hi everyone I have recently started using react native and I have a problem. when I make the network call helpme.php it asks me for the json:

{"person":[{
"girl":{"name":"Alice","id":1},
"boy":{"name":"Json","id":2}},
{"girl":{"name":"Sophia","id":3},
"boy":{"name":"Mark","id":4}}]}

I want to extract the fild name of all names from the json help:me.php file.My code is:

async getDid () {
  let httpResponse = await fetch("https://ewserver.di.unimi.it/mobicomp/treest/getLines.php", {
    method: 'POST',
    headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
    },
    body: JSON.stringify({sid:"Zcoc8cPbnTeXrVJB"})
    });
    const status = httpResponse.status;
    if (status == 200) {
    let deserializedObject = await httpResponse.json();
    console.log(deserializedObject.lines.sname);
    return deserializedObject;
    
    } else {
    let error = new Error("Error message from the server. HTTP status: "   status);
    throw error;
    };    
}

My rusult is: undefined. Why?How can I extract the name field of the file json help_me.php(so i want print Alice,Json,Sophia,Mark) ? What if I want to extract the name field: "Mark"?

CodePudding user response:

For you to print Alice,Json,Sophia,Mark, you need to do

let deserializedObject = await httpResponse.json();

const personArray = deserializedObject?.person ?? [];

const nameArray = [] 
personArray.map((data) => {
nameArray.push(data?.girl?.name)
nameArray.push(data?.boy?.name)
})

console.log(nameArray,"array of anmes")

try this

  • Related