Merging data from JSON data files

How to combine files from Data

data/products_1.json

{
  "fruits": [
  {
    "no": 1,
    "name": "Peer",
    "price": 12,
    "id_product": "1382"
  },
  {
    "no": 2,
    "name": "Watermolen",
    "price": 19,
    "id_product": "1381"
  },
  {
    "no": 3,
    "name": "Blueberry",
    "price": 13,
    "id_product": "1387"
  }
   ]
}

data/products_2.json

{
  "fruits": [
  {
    "no": 1,
    "name": "Orange",
    "price": 1,
    "id_product": "1382"
  },
  {
    "no": 2,
    "name": "Banana",
    "price": 2,
    "id_product": "1381"
  },
  {
    "no": 3,
    "name": "Apple",
    "price": 3,
    "id_product": "1387"
  }
   ]
}

/themes/anythingtheme/layouts/shortcodes/list-products.html
The code below is for example only. Not really running.

{{ $listproduct_1 := .Site.Data.products_1.fruits }}
{{ $listproduct_2 := .Site.Data.products_2.fruits }}

{{ $merge := $listproduct_1 $listproduct_2 }}

<ol>
{{ range $merge }}
    <li>{{.name}} | {{.price}}$</li>
{{ end }}
</ol>

{{< list-products >}}

Result

1. Watermelon | 19$
2. Blueberry | 13$
3. Peer | 12$
4. Orange | 1$
5. Banana | 2$
6. Apple | 3$

I used several methods that exist in the hugo community, none of them worked.

Thanks :slight_smile:

I was looking for a similar implementation and this comes close works!

{{ $listproduct_1 := site.Data.products_1.fruits }}
{{ $listproduct_2 := site.Data.products_2.fruits }}

{{ $merge := $listproduct_1 | append ($listproduct_2) }}

<ol>
{{ range $merge }}
    <li>{{.name}} | {{.price}}$</li>
{{ end }}
</ol>
1 Like

That’s what I came up with. You say it comes close. What’s missing?

1 Like

@TIGA_DUA I bet my previous answer should work for your case.

For me, different ways to sort the values, e.g by price (asc, desc) or alphabetical order.

1 Like
{{ range (sort $merge "price" "desc") }}
{{ range (sort $merge "name" "asc") }}
etc.
2 Likes

That works. I appreciate.

2 Likes

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