简体   繁体   English

JSON错误字符串错误

[英]JSON Bad String Error

I am creating an JSON file which stores some Physics equation, which will be rendered using MathJax. 我正在创建一个存储一些物理方程的JSON文件,它将使用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 有什么方法可以解决此问题而无需更改公式

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). 首先,有效的JSON文件周围将带有{} (正如David Gatti在其回答中提到的,毕竟这是一个对象)。 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: 更正后的JSON应该显示为:

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

JSON is an encoding of structured data. JSON是结构化数据的编码。 You write 你写

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

to mean an object with a property named equations with an array with a single string: 表示具有名为“ equations的属性的对象,该属性带有一个包含单个字符串的数组:

$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. 当JSON解码到对象图中时,它们会被接收器删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM