简体   繁体   English

为什么我的JSON不起作用

[英]Why does my JSON not work

I have a little problem. 我有一点问题。 I have this JSON file 我有这个JSON文件

sprecherText = '[{"name" : "Ashwin","text":"Hi","image":"./images/char1.png"},{"name" : "Abhinandan","text":"Was geht?","image":"./images/char2.png"}]';

I parse it and I can use it nn my script. 我解析它,然后可以在脚本中使用它。

var mydata = $.parseJSON(sprecherText);

But you see that the JSON is not good to read. 但是您看到JSON不好读。 So, I tried to break some lines like this. 因此,我试图打破这种局面。

sprecherText = 
'[{"name" : "Ashwin","text":"Hi","image":"./images/char1.png"},
{"name" : "Abhinandan","text":"Was geht?","image":"./images/char2.png"}]';

but, then I get this error 但是,然后我得到这个错误

sprecherText is not defined sprecherText未定义

Then I tried to make it different like this 然后我试图像这样使它与众不同

{  
"sprecherText":[  
  {  
     "name":"Ashwin",
     "text":"Hi",
     "image":"./images/char1.png"
  },
  {  
     "name":"Abhinandan",
     "text":"Was geht?",
     "image":"./images/char2.png"
  }
]
}

I still get the error 我仍然收到错误

sprecherText is not defined. sprecherText未定义。

Someone have an idea why? 有人知道为什么吗?

Your problem is that you are breaking a literal line without putting a backslach at the end \\ 您的问题是您打破了字面行,而没有在结尾处放退步\\

var sprecherText = 
  '[{"name" : "Ashwin","text":"Hi","image":"./images/char1.png"},\
    {"name" : "Abhinandan","text":"Was geht?","image":"./images/char2.png"}]';

console.log(sprecherText)
'[{"name" : "Ashwin","text":"Hi","image":"./images/char1.png"},{"name" : "Abhinandan","text":"Was geht?","image":"./images/char2.png"}]'

Now this works 现在这有效

JSON.parse(sprecherText)
[ { name: 'Ashwin', text: 'Hi', image: './images/char1.png' },
  { name: 'Abhinandan',
    text: 'Was geht?',
    image: './images/char2.png' } ]

Your example is not working due to breaking a literal line in this example: 您的示例由于在此示例中破坏了文字行而无法正常工作:

sprecherText = 
'[{"name" : "Ashwin","text":"Hi","image":"./images/char1.png"},
{"name" : "Abhinandan","text":"Was geht?","image":"./images/char2.png"}]';

turn it into the following and it will fix the issue: 将其转换为以下内容,它将解决此问题:

var sprecherText = '[{"name" : "Ashwin","text":"Hi","image":"./images/char1.png"}, {"name" : "Abhinandan","text":"Was geht?","image":"./images/char2.png"}]';

In your final example of code your JSON is not actually valid as you are missing a closing } or you need to remove the first { to ensure it is valid. 在最后一个代码示例中,JSON实际上无效,因为您缺少结束符}或者您需要删除第一个{以确保其有效。

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

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