Importing Data from a json file

Posted By Will Moody On , Reading Time - 1 minutes

Snippet

Importing Data from a json file

The idea here is to have a json file that can be edited by Forestry which will then reflect throughout the whole website.

Let's start with the json file, in my case called theme.json and it's created in a directory called data in the root of your website.

{
  "site_name": "Gridsome Goodliness",
  "site_description": "Just Some Little Gridsome Goodness",
  "author": "Will Moody",
  "telephone": "01613727057",
  "telephone_display": "01613 727057",
  "mobile": "07877300332",
  "mobile_display": "07877 300332",
  "address": "21 Street Lane",
  "village": "Blything",
  "city": "Norwich",
  "county": "Norfolk",
  "postcode": "NR13 5EJ",
  "company": "Gridsome Goodness"
}

And of course, you can add any other details you need.

Then to use this in a page or template it's simply a case of returning the data like this:-

<script>
   import settings from '../../data/theme.json'
   export default {
    data() {
      return {
        settings,
       }
     },
   }
</script>

And then to add the data to your template like this:-

<h2>Welcome to {{ settings.site_name }}</h2>

or like this if it's called within a link, see the aria-label:-

<p>Why not try the <a href="/" aria-label="`${settings.site_name} Homepage`">Homepage</a>? or <a href="#" onClick="history.go(-1)">Go Back</a> to your previous page.</p>

You will need to add this:-

- type: document
  path: data/theme.json
  label: Site Information

to your setting.yml file (you can see this article for setting up Gridsome with Forestry).

Once you have this working, upload your website (I use Netlify) to go Forestry set up an account if you don't already have one.

When you add your website to Forestry you will then see a sidebar section called Site Information, when you edit any detail here it will after rebuilding reflect all instances throughout your website.