AndreasInfo
AndreasInfo

Reputation: 1227

Traversing through json after ajax call

I am getting some content of my .json file. It works fine until I want to iterate through some paragraphs with the pattern /paragraph?/ where ? is a single digit. The problem is in

data[lang][/paragraph?/].each(function () {
    $(this)
})

in

function get_content(lang) {
  $.getJSON("src/xml/content.json", function (data) {

    //empty div
    $("#content_about_me").text("");

    //set div
    $("#content_about_me").append(
      "<h2 class='text-center'>" +
        data[lang].header +
        "</h2>" +
        "<h3 class='lead text-center'>" +
        data[lang].subheader +
        "</h3>" +
        data[lang][/paragraph?/].each(function () {
          $(this)
        })
    );
  });
}

Here's my .json:

{
  "en": {
    "header": "myName",
    "subheader": "myProfession",
    "paragraph0": "par0en",
    "paragraph1": "par1en",
    "paragraph2": "par2en",
  },
  "ge": {
    "header": "myName",
    "subheader": "myProfession",
    "paragraph0": "par0ge",
    "paragraph1": "par1ge",
    "paragraph2": "par2ge",
  }
}

I tried jQuery .filter() and .find() and played with some regular expressions, but did not manage to get it work.

I'd appreciate any hint?

Upvotes: 1

Views: 25

Answers (1)

AndreasInfo
AndreasInfo

Reputation: 1227

Thanks to Rory, solved it with:

function get_content(lang) {
  $.getJSON("src/json/content.json", function (data) {
    //empty div
    $("#content_about_me").text("");

    //set div
    var str;
    str = "<h2 class='text-center'>" + data[lang].header + "</h2>";
    $(str).appendTo("#content_about_me");

    str = "<h3 class='lead text-center'>" + data[lang].subheader + "</h3>";
    $(str).appendTo("#content_about_me");

    data[lang].paragraph.forEach(function (value) {
      str = "<p>" + value + "</p>";
      $(str).appendTo("#content_about_me");
    });
  });
}

And:

{
  "en": {
    "header": "myName",
    "subheader": "myProfession",
    "paragraph": ["par0en", "par1en", ...],
  },
  "ge": {
    "header": "myName",
    "subheader": "myProfession",
    "paragraph": ["par0ge", "par1ge", ...],
  },
}

Upvotes: 1

Related Questions