g3ek1337 g3ek1337 - 1 month ago 7
JSON Question

Error parsing JSON which starts with "var ..."

I got into a little thing while getting a JSON file from a server, the JSON file contains something like this:

var reviews = [
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco",
"reviewTitle":"Super quality.. I will show here again!",
"reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
"starRating":"5"
},
{
"firstName":"John",
"lastName":"Smith",
"fullName":"John Smith",
"location":"New York",
"reviewTitle":"Princely Sum",
"reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
"starRating":"4"
},
];


And as expected, I get an error while getting the file with
$.ajax
:

SyntaxError: Unexpected token v


Since is not a valid JSON format, but I did also try to do it with another kind of
dataType
.
My question is:

Is there any way to get that variable in JSON file stored in another variable so it can be manipulated normally?

also I did try to use
FileReader()
but I didn't work for me.

thanks

Answer

JSON is just a way of storing data, not JavaScript code. it doesn't know what to do with var reviews =. All you store in your JSON file is the data, like below.

[
    {
        "firstName":"Simon", 
        "lastName":"Lock",
        "fullName":"Simon Lock",
        "location":"San Francisco",
        "reviewTitle":"Super quality.. I will show here again!",
        "reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
        "starRating":"5"
    }, 
    {
        "firstName":"John", 
        "lastName":"Smith",
        "fullName":"John Smith",
        "location":"New York",
        "reviewTitle":"Princely Sum",
        "reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
        "starRating":"4"        
    }
]
Comments