Search code examples
vue.jsgridsome

How to import and read a json file into Vue / Gridsome main.js


I'm working on a project that is using Vue / Gridsome and have a question about importing a config.json file with import './config.json' into the main.js file.

The config.json files is as follows:

{
  "brand": "Name"
  "company_no": "12345678"
  "charity_no": "87654321"
  "registered_address": "25 Riverdale House: London: SE13 7LW"
  "contact_email": "support@name.com"
}

The main.js file is as follows:

export default function (Vue, { router, head, isClient }) {
  Vue.component('Layout', DefaultLayout)
  Vue.component('Page', PageLayout)
  Vue.use(InfiniteLoading)

  // General

  head.meta.push({
    name    : 'description',
    content : config.brand // I'd like to place the json value here
  })

  // ...

Will I need to install a plugin which parses the JSON to be able to read these properties, and how would I go about accessing the brand value as an example?


Solution

  • You can simply do something like:

    import configJson from './config.json';
    
    const config = JSON.parse(configJson);
    

    Then you can access the data with config.brand for example.

    More about JSON parse:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    EDIT It works if you have webpack >= 2.0.0

    https://webpack.js.org/loaders/json-loader/

    Otherwise you could create a js file and export the json from there:

    config.js

    export default
    {
      // put json here
    }