1

Here is the JSON String I have. I have removed the opening and closing brackets from the JSON because I need to use the JSON values in jQuery to actually load the data in a select box:

{
    "text": "Pediatric FA, CPR & AED (2015)",
    "id": "128177000002431552~Pediatric FA, CPR & AED DVD Set (2015)~YES~117.19"
}, {
    "text": "FA, CPR & AED Manual (2015)",
    "id": "128177000002431564~FA, CPR & AED Manual (2015)~YES~17.73"
}

here is my Javascript Code

$.post("items.cfm",{"term":request.term})
                .done(function(data){
                    try{
                        var obj = JSON.parse(data),
                        values = [];
                        $.each(data, function(i, obj) {
                            values.push({"label":obj[x].text, "value":obj[x].id, "price":obj[x].id.split('~')[3]});
                        })
                        response(values);
                    }catch(e){
                        alert(e);
                    }
                })
                .fail(function(e){
                    alert(e);
                });

every time I run it I am getting the error

SyntaxError: Unexpected token , in JSON at position

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Hane
  • 11
  • 3
  • Have you checked the browser console to see the actual JSON content returned from the HTTP request? And does it really say, "... at position" with no more information? – Pointy Feb 24 '17 at 20:36
  • You can't have multiple objects in a JSON string unless they're encapsulated in square brackets as an array. Add a `[` and `]` on either end of the JSON string to make it valid. – Tyler Roper Feb 24 '17 at 20:37
  • I said in my POST I am removing the start and end brackets, if i do not remove them then i get this error: `TypeError: Cannot use 'in' operator to search for '4592' in` – Hane Feb 24 '17 at 21:07

1 Answers1

3

You have two JSON objects separated by a comma. If you meant this to be an array, you need to surround it with array brackets:

[
{
    "text": "Pediatric FA, CPR & AED (2015)",
    "id": "128177000002431552~Pediatric FA, CPR & AED DVD Set (2015)~YES~117.19"
}, {
    "text": "FA, CPR & AED Manual (2015)",
    "id": "128177000002431564~FA, CPR & AED Manual (2015)~YES~17.73"
}
]

As a side note, if your server is generating invalid JSON, you should take a good look at the code that's producing the JSON. Chances are, there's code trying to generate this string by hand, which is a bad practice. The server should be using a library to convert the returned value into JSON.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • I said in my POST I am removing the start and end brackets, if i do not remove them then i get this error: `TypeError: Cannot use 'in' operator to search for '4592' in ` – Hane Feb 24 '17 at 20:53
  • @Hane: This other error you're getting is another issue entirely, [with its own fix](http://stackoverflow.com/a/18502129/120955). – StriplingWarrior Feb 24 '17 at 23:46