简体   繁体   中英

How to load and print json array/object in javascript

I do not have any json and d3 knowledge (just started to read few hours back) but have very basic javascript knowledge. I have to load a json file and print all the array and objects on the console using d3. I was wondering if anyone can help me to solve it. Actually, I did it but does not work :( My json file.

 {
    "addressfile": "info", 
        "struct": {
          "address": [
               [
                  "A", 
                  "B", 
               ], 
               [
                  "B", 
                  "C", 
               ], 
         ], 

           "address1": {
           "address2": {
           "address3": {
                  "zip": [
                      "NUMBER", 
                        0
                     ]
                  }, 
            "address_type": "Home"
            }, 
         }
     }, 
    "COUNTRY": {}, 
    }

My javascript code...

<!DOCTYPE html>
<meta charset="utf-8">
<style>
<body>
<script>
//LOADING JSON FILE
d3.json("address.json", function(error, root) {
      if (error) return console.error(error);
          for (var p in location) if (location.hasOwnProperty(p)) {
               console.log(p + " : " + location[p]);
           }
       }
 </script>
 </body> 
 </html>

Please help me to solve it...

Try

d3.json("appinfo.json", function(location) { 

I know the docs say the callback takes two parameters, in a project I recently did with d3 version 3.4.13, the callback function would only work if I only passed it the data parameter.

your code missing a closing parenthesis - );

correct code would be :

<script>
    d3.json("appinfo.json", function(error, root) {
         if (error) return console.error(error);

          console.log(root) // output -your JSON data as pojo

          //for (var p in location) if (location.hasOwnProperty(p)) {
          //     console.log(p + " : " + location[p]);
          //}
    });
</script>
  • make sure you write correct url to your json file in first parameter to d3.json().
  • make sure that appinfo.json contain correct json object, you can test it at http://jsonlint.com/

Thanks everyone.. After struggling I got the solution.. Solution: External Json files are not supported by the browsers ..so I needed to use webserver. Then I was able to see the output of it in the console. the final code:

<!DOCTYPE html>
<meta charset="utf-8">
 <head>
   <script src="http://d3js.org/d3.v3.min.js"></script>
 </head>
 <body>
   <script>
        d3.json("address.json", function(location) {
        console.log(location)
  });
   </script>
 </body>
 </html>

Hope it might help others to solve in minutes not in hours like me.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM