3

How can I get the value from this object?

var descipt = "{'type':'" + $('#medi-type option:selected').val() +"',"+
        "'weight':" + $('#weight').val() +","+
        "'weight-type':'" + $('#weight-type option:selected').val() +"',"+
        "'dose':'" + $('#medicine-dose').val() +"',"+
        "'dose-type':'" + $('#dose-type option:selected').val() +"',"+
        "'day-time':'" + morning +"',"+
        "'noon-time':'" + noon +"',"+
        "'night-time':'" + night +"',"+
        "'after':'" + after +"',"+
        "'before':'" + before +"'}";

alert(descipt.weight);

how to get weight from the object.

5
  • 1
    var jsonObj = JSON.parse(descipt); var weight = jsonObj.weight; var weighttype = jsonObj["weight-type"]; and so on... Commented Oct 31, 2017 at 12:53
  • 1
    I don't get the point of doing this. You can simply create a object instead of a string.
    – rrk
    Commented Oct 31, 2017 at 12:54
  • 1
    You can do something like this.
    – rrk
    Commented Oct 31, 2017 at 12:58
  • Possible duplicate of Deserializing a JSON into a JavaScript object Commented Oct 31, 2017 at 13:08
  • If you want to work with the object, why even bother with JSON? Just create an object directly...? Commented Oct 31, 2017 at 13:16

3 Answers 3

8

That's not a JSON object, that's a string. You should first parse it to a JSON object with

var desciptObject = JSON.parse(descipt);

and then you can read weight with

weight = desciptObject.weight;
1

first you need to convert that to a JavaScript object with:

var obj = JSON.parse(descipt);

and after that use like this:

alert(obj.weight);

in fact this is an string and you can not access like a object to nodes.

0
1

Use JSON.parse

var jsonObj = JSON.parse(descipt);
var weight = jsonObj.weight;
var weighttype = jsonObj["weight-type"]; // jsonObj.weight-type  will throw error

Not the answer you're looking for? Browse other questions tagged or ask your own question.