Carlos Pisarello
Carlos Pisarello

Reputation: 1284

Unexpected token < in JSON at position 0 vuejs

I've been looking for how to solve this error but i didn't understand very well how t fix it.

I'm working with lottie-web on a project and i have to set the params of the animation on an object to pass it as a parameter later.

My component:

import Lottie from './../../node_modules/lottie-web/build/player/lottie';

export default {
  name: 'Illustration',
  mounted() {
    this.animationParams = {
      container: document.getElementById('animation'),
      renderer: 'svg',
      loop: 'true',
      autoplay: 'false',
      path: '/src/data/animation.json',
    };
    Lottie.loadAnimation(this.animationParams);
  },
  data() {
    return {
      animationParams: {
      },
    };
  },

but when this line is executed:

    Lottie.loadAnimation(this.animationParams);

i get this error:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange

what i have seen on other answers here in Stackoverflow is that i don't have to parse the json since it's already parsed, but i don't know how to NOT parse it.

here's what's inside the json file: http://myjson.com/s0kn6.

how do i have to load that json file without parsing it?

Upvotes: 3

Views: 7289

Answers (1)

Bert
Bert

Reputation: 82489

It's unlikely your server is serving /src/data/animation.json. Instead of using path use animationData and just set the animation object directly (instead of via a server call).

First, I would just set the animation data to a regular ES6 module that exports an object instead of json.

/src/data/animation.js

export default {
  // your animation data
}

Note that it's a javascript file, not a json file. Then in your component, just import the object.

import Lottie from './../../node_modules/lottie-web/build/player/lottie';
import animationData from "/src/data/animation"

export default {
  name: 'Illustration',
  mounted() {
    this.animationParams = {
      container: document.getElementById('animation'),
      renderer: 'svg',
      loop: 'true',
      autoplay: 'false',
      animationData,
    };
    Lottie.loadAnimation(this.animationParams);
  },
  data() {
    return {
      animationParams: {
      },
    };
  },

This is documented here.

This will make your initial bundle larger, but you won't have to make an additional call to the server for the animation data.

Barring that, you will need to move animation.json to some path that is being served by your server and set path to a url relative to the page that is currently loaded.

Upvotes: 1

Related Questions