0

I am creating an JSON file which stores some Physics equation, which will be rendered using MathJax.

"equations": [
    "$w = F.s\cos\theta$"
 ]

I am getting a bad string error. I have tried adding another backslash before the slashes but that changes the equations drastically. Is there any way to fix this issue without changing the equation

Sukrit Kumar
  • 375
  • 4
  • 20

2 Answers2

4

There were two issues you were falling over.

Firstly, a valid JSON file will have { and } around it (as David Gatti mentions in his answer, it is an object after all). Secondly, certain characters - including backslashes - will need to be escaped. When you parse it back into an object, the additional backslashes will be removed.

Your corrected JSON should read:

{
    "equations": [
        "$w = F.s\\cos\\theta$ "
    ]
}
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
1

JSON is an encoding of structured data. You write

{
  "equations": [
    "$w = F.s\\cos\\theta$"
  ]
}

to mean an object with a property named equations with an array with a single string:

$w = F.s\cos\theta$

The escaped backslashes (\) does not change the underlying data. They get removed by the receiver when the JSON gets decoded into the object graph.

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138