-4

How to print this hash Table data in java script

var product = {
    "prduct_name": "Mobile",
    "product_attribute": {
        "attribute_name": "Brand",
        "type": "combo",
        "product_attribute_values": {
            "attribute_value": "Apple",
            "brand_price": "2000"
        }
    }
};
Manse
  • 37,765
  • 10
  • 83
  • 108
Aslam Khan
  • 67
  • 1
  • 2
  • 5
  • 4
    What have you tried? What doesn't work? What is your target platform (web browser? jQuery? JScript? Node.js)? – maerics Apr 13 '12 at 13:16
  • I assume that the question must be more complicated than you're stating here. After all, if your objective really was just to display a string (however arbitrary) doing so in HTML is trivial, and doing so in javascript (why would you not just do it in HTML?) only slightly less so. – Ben Barden Apr 13 '12 at 13:19
  • how to print hash key and values with nested hash key with values?? – Aslam Khan Apr 13 '12 at 13:32

2 Answers2

11

If your (or target) browser has the JSON object available ( Internet Explorer 8+, Firefox 3.1+, Safari 4+, Chrome 3+, and Opera 10.5+ Browser-native JSON support (window.JSON) ) then I suggest as a quick development sol.

str = JSON.stringify(product);

or if you want it all pretty like:

str = JSON.stringify(product, null, " ");

This will probably not be appropriate for a client facing display however!

Community
  • 1
  • 1
Arth
  • 12,789
  • 5
  • 37
  • 69
  • 2
    This will work but you must have JSON in the page which is not available on all browsers – GillesC Apr 13 '12 at 13:39
  • Support is pretty good for JSON -> Internet Explorer 8+, Firefox 3.1+, Safari 4+, Chrome 3+, and Opera 10.5+ – Arth Apr 13 '12 at 13:47
  • true, I guess sometimes with those questions poster should let us know what are they aiming to support. – GillesC Apr 13 '12 at 13:51
  • Thanks for the hint, have updated the answer to show additional info – Arth Apr 13 '12 at 14:00
0

Edited as didn't saw the nested object data.

http://jsfiddle.net/wYWQJ/

function printData(data) {
    var str = '';
    for (var key in data) {
        if (typeof data[key] == 'object') str += key + printData(data[key]) + ' ';
        else str += key + ' => ' + data[key] + ' ';
    }
    return str;
};

console.log(printData(product));
GillesC
  • 10,647
  • 3
  • 40
  • 55
  • Don't forget wrapper characters around the outside of each key/product pair. Currently, your version has product[n] and key[n+1] butting up against one another in a potentially indistinguishable way. – Ben Barden Apr 13 '12 at 13:21
  • How to print all key with values?? – Aslam Khan Apr 13 '12 at 13:21