Search code examples
jsonjekyllliquid

Correct syntax for addressing JSON object in Jekyll _data file


I am creating a page in Jekyll and attempting to use data in a JSON file stored in Jekyll's "_data" folder. The JSON file is "/_data/objectsandproperties.json" and contains:

{ 
    "objectA": { "propertyA": "FooA", "propertyB": "BarA" },
    "objectB": { "propertyA": "FooB", "propertyB": "BarB" },
    "objectC": { "propertyA": "FooC", "propertyB": "BarC" }
}

I would like to output a list formatted like this:

<dl>
    <dt>objectA</dt>
        <dd>propertyA: FooA</dd>
        <dd>propertyB: BarA</dd>
    <dt>objectB</dt>
        <dd>propertyA: FooB</dd>
        <dd>propertyB: BarB</dd>
    <dt>objectC</dt>
        <dd>propertyA: FooC</dd>
        <dd>propertyB: BarC</dd>
</dl>

I am currently using Liquid tags in my markdown file like this:

{% for objects in site.data.objectsandproperties %}
<dl>
  {% for object in objects %}
  <dt>Object names: {{ object }}</dt>
      <dd>propertyA: {{ object.propertyA }}</dd>
      <dd>propertyB: {{ object.propertyB }}</dd>
  {% endfor %}
</dl>
{% endfor %}

This is not working as the object is not "objectA" but the entire objectA object with properties etc.

I don't have access to the script that creates the JSON file so I cannot add a label or make it an array etc. I'm hoping I can get this to work with Liquid.

Thanks.


Solution

  • Using the inspect filter to better understand what we are working with :

    {% for object in site.data.objectsandproperties %}
    
      {{ object | inspect }} 
      >> returns an array like :
      >> ["objectA", {"propertyA"=>"FooA", "propertyB"=>"BarA"}]
    
      name : {{ object.first }} or {{ object[0] }}
      properties : {{ object.last}} or {{ object[1] }}
    
    {% endfor %}
    

    Your code can look like :

    <dl>
    {% for object in site.data.objectsandproperties %}
      <dt>Object names: {{ object | first }}</dt>
      <dd>propertyA: {{ object.last.propertyA }}</dd>
      <dd>propertyB: {{ object.last.propertyB }}</dd>
    {% endfor %}
    </dl>