How Can I Read JSON File Contents in Templater Script in Obsidian?

Hey everyone,

I’m trying to read the contents of a JSON file in an Obsidian note using a Templater script. I’m familiar with Templater and basic scripting, but I’m not sure of the best way to load and parse a JSON file.

Here’s what I have so far:

const exerciseFile = tp.file.find_tfile("test.json");

I can locate the file, but I’m unsure how to read its content properly. I assume it involves using JavaScript’s fs module or another method, but I’m not entirely clear on the process within Templater’s environment.

Any tips or examples on how to:

1.	Load the JSON file.
2.	Parse its contents for use in the script.

Thanks in advance for the help!

The last time I’ve played around with JSON and Templater, I got it to work using something like:

<%*
const jsonPath = "JSON/test.json";
// Get the TFile of the json
const jsonTFile = app.vault.getFileByPath(jsonPath);
// Read the json TFile
const json = await app.vault.read(jsonTFile);
// JSON parse method
let o = JSON.parse(json);
// Optional console check
console.log(o)
-%>
<% o.glossary.title %>

To read the JSON, I actually rely on Obsidian API :blush: : see read - Developer Documentation
(and yes, in this case, I intended to try and modify the JSON using Templater too, this is why I used the app.vault.read() instead of app.vault.cachedRead() per Obsidian dev documentation :innocent: )

For JSON.parse(): JSON.parse() - JavaScript | MDN

The snippet above, following the test.json below, outputs in a note when the template runs:

example glossary

test.json content:

{
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  },
  "newKey": "newValue",
  "newKeyAgain": "newValue or something",
  "newKeyTest": "newValue",
  "property1": {
    "value": 42,
    "writable": false
  },
  "property2": {
    "value": 1,
    "writable": true
  },
  "property3": {
    "value": 2,
    "writable": true
  },
  "property4": {
    "value": 1,
    "writable": false
  }
}

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