I have a json file that looks like this:
status: [
{
"0":"val",
"1":"val",
"2":"val"
},
{
"0":"val",
"1":"val",
"2":"val"
}
]
I have numbers as keys in json file but I am not able to select those inside my templates. I also considered changing the numbers into words but the size of the file is humongous. Is there a way to select number keys inside templates?
Number keys are not allowed, as far as I know.
Okay. Thanks. I guess I’ll have to find a way to convert numbers to words.
Are your keys always starting and counting up from 0? Then you can just leave them out. Check this answer on stackoverflow about this:
Your keys are not numbers; they are string representations of numbers. This only presents a problem when trying to access the corresponding values using dot notation.
TLDR: Use the index function.
Example 1
data/status.json
[
{
"a": "foo",
"b": "bar",
"c": "baz"
}
]
code
{{ range .Site.Data.status }}
dot notation: {{ .a }}<br>
index function: {{ index . "a" }}<br>
{{ end }}
result
dot notation: foo
index function: foo
Example 2
data/status.json
[
{
"0": "wibble",
"1": "wobble",
"2": "wubble"
}
]
code
{{ range .Site.Data.status }}
dot notation: {{ .0 }}<br>
index function: {{ index . "0" }}<br>
{{ end }}
result
dot notation: 0
index function: wibble
This is perfect! Thank you.