Reputation: 5408
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.
Upvotes: 0
Views: 110
Reputation: 5408
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'
Upvotes: 0
Reputation: 61
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.
Upvotes: 1