Extract JSON

Hi All,

I have a JSON data something like below under the content/post/post1.

The links in the JSON changes for every post.

urls.json

{
    "url": [
        { "link": "https://google.com", "label": "Google" },
        { "link": "http://gohugo.io/", "label": "Hugo" },
     
    ]
}

How do I extract?

I tried

{{ range .Site.Dir.urls.url }}

But, it didn’t work.

Can some one help me.

Give this a try:

{{ $json := getJSON "content/post/post1/urls.json" }}

{{ range $json.url }}
  {{ . }}
{{ end }}

Thank you for your response.

I dont know how to explain.

My url will be like

example.com/post/post1
example.com/post/post2

In relative to data,

It will be

content/post/post1/index.md
content/post/post2/index.md

My requirment is, every post will have different urls.json file under it.

urls.json

{
    "url": [
        { "link": "https://google.com", "label": "Google" },
        { "link": "http://gohugo.io/", "label": "Hugo" },
     
    ]
}

Need to extract them

See

and

Then you need to build your path value per-page. For example, put something like this in your layouts/_default/single.html template:

{{ $path := printf "content/%s/urls.json" .File.Dir }}

{{ $json := getJSON $path }}

{{ range $json.url }}
  {{ . }}
{{ end }}

Thanks Zachary.

Your code works for me.

One more thing.

is it possible? if the JSON file doesn’t exist, it should not display or not build.

In post 3, I don’t have a JSON file and it is giving below error.

Building sites … ERROR 2019/10/22 02:55:51 Failed to get JSON resource “content/post/post3/urls.json”: unexpected end of JSON input

For post1 and post2, I have no issues as they have JSON files.

Thanks.

Did you ever get this working? I expect so, but if not, here is how I did it. First, I’m using page bundles, and I put the JSON file in the directory of the page bundle. Then I had to tweak your JSON file to look like this

[
    	"url": [
            { "link": "https://google.com", "label": "Google" },
            { "link": "http://gohugo.io/", "label": "Hugo" },
	]
]

Then I had a partial that did this:


{{- with .Resources.GetMatch "urls.json" -}}
  {{- $json := unmarshal .Content -}}
  {{- range $json -}}
  <ul>
     {{ range .url }}
       <li><a href="{{ .link }}">{{ .label }}</a></li>
     {{ end }}
  </ul>   
  {{- end -}}
{{- end -}}

That gave me a nice list of the links and and the labels … is that what you kind of wanted?