1

I have a JSON object as below:

{"_id":"594fe31b3e158c0e70c9bb3e","deviceid":"342","alldata":"{\"deviceid\":\"342\",\"voltage\":\"14\",\"current\":\"9\",\"power\":\"92\",\"status\":\"1\"}","receivedon":"2017/06/25 21:51:47","__v":0}

The issue is that, when I try to output obj.alldata.voltage, it just gives blank; which leads me to think that obj.alldata is a string and not a JSON object.

When I print obj.alldata, it gives an output like:

{"deviceid":"342","voltage":"14","current":"9","power":"92","status":"1"}

How can I use obj.receivedon, as well as obj.alldata.voltage, correctly?

3
  • try jsonifing obj.alldata Commented Jun 25, 2017 at 17:20
  • You should use the parse() function in JS, and the data becomes a JavaScript object. Commented Jun 25, 2017 at 17:22
  • "which leads me to think that obj.alldata is a string and not a JSON object" exactly. There is no such thing as a JSON object. You have to understand with what types you are dealing. You either have an object, or a string (wich may or may not contain JSON). And you can only access the properties on the object, not on the string. Commented Jun 25, 2017 at 17:46

2 Answers 2

1

Remove the quotes of the alldata value, so it won't be treated as string.

{ "_id": "594fe31b3e158c0e70c9bb3e", "deviceid": "342", "alldata": { "deviceid":"342","voltage":"14","current":"9","power":"92","status":"1"}, "receivedon": "2017/ 06 / 25 21: 51:47", "__v": 0 };
Sign up to request clarification or add additional context in comments.

Comments

0
data = {
        "_id": "594fe31b3e158c0e70c9bb3e",
        "deviceid": "342",
        "alldata": {\"deviceid\":\"342\",\"voltage\":\"14\",\"current\":\"9\",\"power\":\"92\",\"status\":\"1\"}",
        "receivedon": "2017/06/25 21:51:47",
        "__v": 0
       }

The above is a hash or a js object except the value for key "alldata" is a json, you need to parse that json

data.alldata = JSON.parse(data.alldata)

After this your object will look like this

     { _id: "594fe31b3e158c0e70c9bb3e", 
       deviceid: "342", : 
       alldata: {
          deviceid: "342",
          voltage: "14",
          current: "9",
          power: "92",
          status: "1"
      }, 
     receivedon: "2017/06/25 21:51:47", __v: 0
    }

Comments

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.