S.Kawa
S.Kawa

Reputation: 11

Why does my JSON not work

I have a little problem. I have this JSON file

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. 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

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.

Someone have an idea why?

Upvotes: -1

Views: 212

Answers (2)

Ryank
Ryank

Reputation: 507

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.

Upvotes: 2

Soren
Soren

Reputation: 14718

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' } ]

Upvotes: 3

Related Questions