简体   繁体   中英

parse my json to get values - json sent from Xcode to JS front-end

Trying to parse and read my JSON data.
I am passing my json data from Xcode to my React native front-end.
I have tried JSON.parse and JSON.stringify nothing works.
It always logs "NULL". I need to access the "value" Help please!!

JSON in Xcode

{
  "myDictionary" : {
    "BG" : [
      "{\"value\":\"8 mg\\\/dL\",\"endDate\":635390040,\"startDate\":635390040,\"type\":\"bloodGlucose\"}",
      "{\"value\":\"6 mg\\\/dL\",\"endDate\":635393640,\"startDate\":635393640,\"type\":\"bloodGlucose\"}"
    ]
  }
}

JS:

const log = HealthkitController.getBloodGlucose()
    .then(result => {
     let res = JSON.parse(result)
      for (let i = 0; i < res.length; i++) {
        let final = res[0];        
        console.log(final)         // prints the first object
        let fin = final["value"]
        console.log(fin)           //undefined (doesn't print 8mg/dL)
 }
})

result:

["{\"value\":\"8 mg\\\/dL\",\"endDate\":635390040,\"startDate\":635390040,\"type\":\"bloodGlucose\"}",
"{\"value\":\"6 mg\\\/dL\",\"endDate\":635393640,\"startDate\":635393640,\"type\":\"bloodGlucose\"}"]

What does this create?

 const log = HealthkitController.getBloodGlucose().then(result => { for (var i = 0; i < result.lenght; i++{ let res = JSON.parse(result[i]) console.log(res) //always null } });

Your result is coming back as an Array of strings. If you want to extract the value you can do something like this

const values = results.map(result => {
 const { value } = JSON.parse(result);
 return value;
});

The output will be:

["8 mg/dL", "6 mg/dL"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM