0

I am trying to retreive the values present in the JSON Array.However,my code is failing to get it executed.Below posted is how the file looks like.

{
  "meta" : {
    "view" : {
      "description" : "This data set shows the location of Baltimore City's Services.",
      "columns" : [{
          "cachedContents" : {
            "top" : [{
                "item" : "American Rescue Workers"
              }
            ]
          }
        }
      ]
    }
  }

My Apologies if my JSON file has got some syntax issues.I am trying to access the item element present in cachedContents.Below posted is the code.

$(document).ready(function () {

    $.get("https://data.baltimorecity.gov/api/views/hyq3-8sxr/rows.json", function (data) {
        $.each(data.meta.view, function (i, obj) {
            if (i == "name")
                $("#result").append("<p align='center'>" + obj + "</p>");
            if (i == "description")
                $("#result").append("<p>" + obj + "</p>");
            if (i == "columns")
                $.each(obj.i.cachedContents, function (i1, obj) {
                    $("#result").append("<p>" + "hi" + "</p>");
                });
        });
    });

});

Any suggestions would be highly helpful.

1
  • you never really access the item element...you do not event try to... Commented Dec 8, 2015 at 4:57

2 Answers 2

3

Your JSON contains a lot of fields, and iterating through them and using if may have some performance issues.

You can directly access every member instead:

$(document).ready(function () {

  $.get("https://data.baltimorecity.gov/api/views/hyq3-8sxr/rows.json", function (data) {			
    $("#result").append("<p align='center'>" + data.meta.view.name + "</p>");
    $("#result").append("<p>" + data.meta.view.description + "</p>");

    data.meta.view.columns.forEach(function(c) {
      // here, 'c' is a column
      $("#result").append("<p>Column " + c.name + "</p>");
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="result"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

However,It is not printing the cachedContents in it right?
1

It should be

$.each(obj[0].cachedContents, function(i1, obj) {
      $("#result").append("<p>" + "hi" + "</p>");
    });

Object[0] not "i".

2 Comments

does this code actually appends anything at all in #result?
No, I don't think so. The OP may want to iterate the obj to append something, not only the obj[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.