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.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Naveen Roy
  • 85
  • 12
  • 1
    var jsonObj = JSON.parse(descipt); var weight = jsonObj.weight; var weighttype = jsonObj["weight-type"]; and so on... – Yogesh Chuahan Oct 31 '17 at 12:53
  • 1
    I don't get the point of doing this. You can simply create a object instead of a string. – rrk Oct 31 '17 at 12:54
  • 1
    You can do something like [this](http://jsfiddle.net/zvw0zgw3/2/). – rrk Oct 31 '17 at 12:58
  • Possible duplicate of [Deserializing a JSON into a JavaScript object](https://stackoverflow.com/questions/6487167/deserializing-a-json-into-a-javascript-object) – Sanchit Patiyal Oct 31 '17 at 13:08
  • If you want to work with the object, why even bother with JSON? Just create an object directly...? – Rory McCrossan Oct 31 '17 at 13:16

3 Answers3

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;
Luca De Nardi
  • 2,280
  • 16
  • 35
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.

Majid Abbasi
  • 1,531
  • 3
  • 12
  • 22
1

Use JSON.parse

var jsonObj = JSON.parse(descipt);
var weight = jsonObj.weight;
var weighttype = jsonObj["weight-type"]; // jsonObj.weight-type  will throw error
Yogesh Chuahan
  • 358
  • 2
  • 11