Skip to content
Advertisement

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

Advertisement

Answer

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"]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement