Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json string values in javascript

I have following JSON string in a global variable in Javascript

var domains = {
    "DomID00001": {
        "ID":"DomID00001",
        "Name":"Testdomein1"
    },
    "DomID00002": {
        "ID":"DomID00002",
        "Name":"Testdomein2"
    }
};

What is the best way to retrieve the values from this JSON string and be able to use them in Javascript individually?

If I just alert the domains var it says = [object Object]

like image 944
Filip Huysmans Avatar asked Sep 17 '26 05:09

Filip Huysmans


2 Answers

Using alert() will not show you objects, this is one of the big advantages of the console. Check this fiddle and use the console (pressing F12 on your browser). Then you understand how to refer to what is inside that object.

var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};

console.log(domains);
console.log(domains.DomID00001);
console.log(domains.DomID00001.ID);
like image 128
Sergio Avatar answered Sep 22 '26 14:09

Sergio


Since the keys are variable, you should probably use a for..in loop:

for( domid in domains) if( domains.hasOwnProperty(domid)) {
    console.log(domid,domains[domid].ID,domains[domid].Name);
}
like image 31
Niet the Dark Absol Avatar answered Sep 22 '26 13:09

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!