1

I'm using json2html and trying to figure out the correct syntax for calling JSON data within an array:

{ biographicData: [
    {
        firstName: 'John',
        lastName: 'Doe',
        birthDate: '10/15/1983',
        email: 'johndoe@gmail.com',
        workPhone: '678-901-2345',
        mobilePhone: '098-765-4321',
        homePhone: '123-456-7890'
    }
]}

In other cases, I've used something like {"tag":"div","html":"${biographicData.firstName}"} to get the values, but that doesn't seem to work when the data is in an array. What do I need to do to fix this call?

1 Answers1

1

To access array data you can do something like this if you know the position of the array you are trying to access

{"tag":"div","html":"${biographicData.0.firstName}"}

or you could transform the entire array (if there are multiple elements) using an inline function and a transform

{"tag":"div","children":function(){
   return( json2html.transform(this,bioDataTransform) );
}}
Chad Brown
  • 1,627
  • 1
  • 13
  • 22
  • How would this work with the `required` array in data such as: [{ "name": "Lorem", "types": ["add"], "important": false, "institution": "something" }, { "name": "Ipsum", "types": ["copy"], "important": false, "required": ["one", "two"] } ] ? Thanks! – karkraeg Jun 05 '19 at 09:06
  • I take it you want to render the "required" array you could use a transform like this on the data {"<>":"div","html":[ {"<>":"div","text":"${name}"}, {"<>":"div","html":function(){ return( this.required.join(",") ); } } – Chad Brown Jun 06 '19 at 16:10
  • This outputs the same as when I simply call it by `${required}"` – I’m looking for a way to iterate over the array and output elements as `
  • ` elements in html. Working with a for-loop to iterate over the array only returns the first value of the required array... `{"<>": "div", "class": "panel-footer", "html": function () { var arr = this.required; for (var i = 0; i < arr.length; i++) { var element = arr[i]; return "
  • " + element + "
  • "; } } }` – karkraeg Jun 07 '19 at 06:12
  • I got it like this: `{ "<>": "div", "class": "panel-footer", "html": function () { var arr = this.required; var output = []; if (arr == undefined) { return "Keine requirements"; } else { for (var i = 0; i < arr.length; i++) { var element = arr[i]; output.push(element); } return output.join(""); } } }` – karkraeg Jun 07 '19 at 06:40
  • You could also do it like this if you want it as a list ... { "<>": "ul", "class": "panel-footer", "html": function () { var output = []; if (!this required) { return "Keine requirements"; } else { for (var i = 0; i < this.required.length; i++) { output.push({"val":arr[i]}); } return json2html.transform(output,{"<>":"li","text":"${val}"}) } } } – Chad Brown Jun 08 '19 at 16:55