Reputation: 25
I am getting the variable from a json file that is
var node = data.nodes;
alert(node);
returns the following
[{"name" : "30","group": 0} , {"name" : "40","group": 0} ]
which is not an Object
If I assign this value directly to a variable then it is counted as object as you can see below.
var node = [{"name" : "30","group": 0} , {"name" : "40","group": 0} ]
Why is the value not an Object in the first place? What can I do to convert the variable to an Object?
any help would be truly appreciated.
Upvotes: 0
Views: 50
Reputation: 700372
You can use the JSON.parse method to turn the string into an object:
var node = JSON.parse(data.nodes);
Note that some older browsers (e.g. IE 7) doesn't support the JSON
object. You can read more about that on the documentation page that I linked to if you need to support older versions.
Upvotes: 4
Reputation: 3925
Try this:
<script type="text/javascript">
var node = data.nodes //[{"name" : "30","group": 0} , {"name" : "40","group": 0} ]
var data = JSON.parse(node);
console.log(data); //{name: "30", group: 0}, {name: "40", group: 0}
console.log(data[0]); //{name: "30", group: 0}
</script>
Upvotes: 3