Search code examples
javascriptvue.jsgridsome

How to use JSON/YAML file with Gridsome


I want to build a gridsome application which works with json or YAML file.

I want to get values of files located at "./data/" folder from Vue components and keep the graphQL data layer. In other terms, expose in graphQL data from files.

profile.json

{
    "name": "Lorem"
}

config.json

{
    "layout": "default",
    "theme": "blue"
}

I want to access the name value in a way like this:

$page.data.profile.name
$page.data.config.theme

Or

$data.profile.name
$data.config.theme

have I to deal with @gridsome/source-filesystem and @gridsome/transformer-json plugins ? Or maybe manually adding the 'Data' collection in server and add new node for each file ?

I have tested both and exploring graphQL API return an error : "Unexpected token < in JSON at position 0"

Thanks


Solution

  • If you have local files, you can add them this way:

    import temperatures from '~/data/four.json'
    import east from '~/data/east.json'
    import southwest from '~/data/southwest.json'
    import whd from '~/data/whd.json'
    import thirteen from '~/data/thirteen.json'
    
    export default {
      data () {
        return {
          temperatures,
          east,
          thirteen,
          whd,
          southwest,
        }
      },
    

    Basically i created a data folder within my pages directory and then placed the files in their. You then link to them in the script tag and call for them with a return function.

    In your template tag you would do something like this:

    <template>
    <div>
     {{ temperatures }}
    </div>
    </template>