0

getting the same error in JSON, user is the textbox value which is then pass in JSON for setting class level permissions in parse server

var cc = "role:" + user;
var jsonParam = "{ 'classLevelPermissions' :
                    { 'get':
                        { '*': true, '" + cc + "'  :  true },
                      'find':
                        {'*': true,'" + cc + "'  :  true },
                      'create':
                        { '" + cc + "'  :  true },
                      'update':
                        { '" + cc + "' :  true },
                      'delete':
                        { '" + cc + "'  :  true }
                    }
                 }";
const result = this.http.post(this.url,
    {
        "reqparam": JSON.parse(jsonParam)
    }, httpOptions).toPromise();
console.log(result);

please help me to solve this.

Krunal Shah
  • 836
  • 8
  • 25

2 Answers2

1

Welcome to StackOverflow :)!

You get a syntax error while parsing JSON because the JSON you wrote contains a single quote ', which is an invalid character in JSON. Instead of single quotes ' you should use double quotes ".

To include double quotes in a JavaScript string you will have to escape them. There is another StackOverflow answer pointing that out: https://stackoverflow.com/a/21672439/7437032

Applied to your use case that means changing the jsonParam like this:

var jsonParam = "{ \"classLevelPermissions\" : { \"get\": { \"*\": true, \"" + cc + "\"  :  true }, \"find\": {\"*\": true,\"" + cc + "\"  :  true }, \"create\": { \"" + cc + "\"  :  true }, \"update\": { \"" + cc + "\" :  true }, \"delete\": { \"" + cc + "\"  :  true } } }";

Since this is not very readable and you have multiple variables in your string I propose using JavaScript template strings instead. (Just for clean code ) Here is the documentation for JavaScript template strings: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/template_strings

Applied to your use case:

var jsonParam = `{ "classLevelPermissions" : { "get": { "*": true, "${cc}"  :  true }, "find": {"*": true,"${cc}"  :  true }, "create": { "${cc}"  :  true }, "update": { "${cc}" :  true }, "delete": { "${cc}"  :  true } } }`;
friedow
  • 539
  • 4
  • 3
0

Wrap the text in `` (backticks) and use double quotes for json keys, pass cc as string interpolation.This should fix parse error.

var cc = "role:" + user;
var jsonParam = `{ "classLevelPermissions" : { "get": { "*": true, " ${cc} "  :  true }, "find": {"*": true," ${cc}"  :  true }, "create": { " ${cc}"  :  true }, "update": { "${cc}" :  true }, "delete": { " ${cc} "  :  true } } }`;
Nenad Radak
  • 3,550
  • 2
  • 27
  • 36