Combining json values

I have a json file that contains what is below:

{
“id”: “xmas-trees-1”,
“name”: “Christmas Trees (set of 3)”,
“price”: 40.00,
“weight”: 71,
“length”: [4,1],
“width”: [2,1],
“height”: [13,1],
“images”: ["/store/xmas-trees-1_1.jpg"],
“description”: “”,
“wood”: [“Walnut”, “Maple”],
“finish”: [“Danish Oil”],
“inventory”: 0,
“product_url”: “https://jamieflarity.com/store”,
“product_category”: “Christmas”
},

I have the following in a partial:

<ul>
<li>
{{ if .diameter }}
{{ range $index, $diameter := .diameter }}
{{ $diameter = div $diameter 2.54 }}
{{ $diameter = lang.NumFmt 2 $diameter }}
{{ $diameter }}" D x
{{ end }}
{{ end }}
{{ if .length }}
{{ range $index, $length := .length }}
{{ $length = div $length 2.54 }}
{{ $length = lang.NumFmt 2 $length }}
{{ $length }}" L x
{{ end }}
{{ end }}
{{ if .width }}
{{ range $index, $width := .width }}
{{ $width = div $width 2.54 }}
{{ $width = lang.NumFmt 2 $width }}
{{ $width }}" W x
{{ end }}
{{ end }}
{{ if .height }}
{{ range $index, $height := .height }}
{{ $height = div $height 2.54 }}
{{ $height = lang.NumFmt 2 $height }}
{{ $height }}" H
{{ end }}
{{ end }}
</li>
</ul>

The way that I want to display it is like:
<ul>
<li>1.57" L x 0.79" W x 5.12" H</li>
</ul>

and it works like I want it to. But if I add another measurement to the length, width, or height array it displays like

<ul>
<li>(number)" L x (number)" L x (number)" W x (number)" W x (number)" H x (number)" H</li>
</ul>

What I’m trying to accomplish is it to display like:
<ul>
<li>(number)“L x (number)” W x (number)" H</li>
<li>(number)“L x (number)” W x (number)" H</li>
</ul>

I’m sure I’m missing something simple but I’ve been working on this for a couple of days and can’t find anything online to point me in the right direction. Can anyone help me out?

Thanks!

You tell the script to range through length, then range through width, which is basically what it does :wink:

Can you change the “layout” of your JSON file? Then try the following:

...
"measurements": {
[ 
"length": 4,
"width": 3,
"height": 1
],
[ 
"length": 4,
"width": 3,
"height": 1
]
}
...

And then range through measurements:

{{ range $measurements }}
{{ with .length }}{{ . }} Lx {{ end }}
... etc

If that is not possible you can try the following (no code, just the idea):

  • range through length only
  • output length parameter
  • get index of length item and look for identical index in width and height and output those
1 Like

This entire time I never thought about changing the json file. That works. THANK YOU!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.