0

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

5
  • Can you show what actually is inside result? Commented Feb 19, 2021 at 9:19
  • Please confirm if 'result' is getting the stringified response then only JSON.parse will work. As of now, only BG node contains the stringified objects as elements. Commented Feb 19, 2021 at 9:28
  • @DiwakarSingh check question. I added result. I want to access the value. Commented Feb 19, 2021 at 9:49
  • Try - JSON.parse(myDictionary.BG[0]).value Commented Feb 19, 2021 at 9:59
  • it prints undefined bro Commented Feb 19, 2021 at 10:10

2 Answers 2

0

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"]
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

"result" contains my JSON (check updated question). I want to access the value.
check my updated code. it prints "undefined"
yes, because you have walk through the array. Wait 2 minutes, I will fix this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.