0

From what I understand the json specification has first calss support for methods/functions.

I have the following json file that I am using as a test fixture.

{
  "tokenParsed": {
    "preferred_username": "Test User"
  },
  "hasResourceRole": function () {
    return function (role, resource) {
      if (role && resource) {
        return true
      }
    }
  }
}

If I try to import the file into my VueJS project with

import { keycloak_test_user } from './fixtures/keycloak_test_user.json'

I get the following error

SyntaxError: Unexpected token ( in JSON at position 89
        at JSON.parse (<anonymous>)

      2 | import Vuex from 'vuex'
      3 | import Permission from '@/components/user/Permission.vue'
    > 4 | import { keycloak_test_user } from './fixtures/keycloak_test_user.json'

The above json works fine if I add it directly in my test file rather than importing it.

Although, the error says JSON.parse, I am not sure if that is because webpack is not laoding the file correctly or if JSON.parse is a direct cause for the error, however, even VSCode json formatting sees the function as invalid json.

2 Answers 2

1

In general you can't store functions in json. There are ways to do it but that does not mean it is a good idea. Check the accepted answer in this stackoverflow question for a possible solution. I would not recommend doing it though and ask yourself why you need to store the function in the first place and if there is a better solution for your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Because Keycloak returns help functions in the json object it returns when you login and the code I am testing relies on these methods and functions. JSON has first class support for methods/functions
0

I have solved the problem by replacing my .json file with a .js file like so

  const keycloak = {
    tokenParsed: {
      preferred_username: "Test User"
    },
    hasResourceRole: () => {
      return (role, resource) => {
        if (role && resource) {
          return true
        }
      }
    }
  }

  export default keycloak

I can then import as normal with

import keycloak from './fixtures/keycloak_test_user'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.