0

How can i parse the following json string without the opening and closing quotes? Its seems like javascript JSON.parse function is parsing the string with the quotes! hence throws a syntax error.

This is my string;

"[
    {
        "pk": 1,
        "model": "pms.category",
        "fields": {
            "name": "Rent",
            "add_date": "2011-07-28 01:33:21",
            "agent": 3,
            "category_type": "I",
            "add_user": 3,
            "desc": "Rent"
        }
    },
    {
        "pk": 2,
        "model": "pms.category",
        "fields": {
            "name": "Deposit Rent",
            "add_date": "2011-07-28 01:33:21",
            "agent": 3,
            "category_type": "I",
            "add_user": 3,
            "desc": "Rent Deposit"
        }
    }
]"

Edit: Something interesting is that when i run this string of my development machine, it is parsed correctly, but on the production server it fails.

gath
  • 24,504
  • 36
  • 94
  • 124

3 Answers3

3

Replace the opening and closing quotes, and then parse the string:

s = s.replace(/^"|"$/g, '');
var jsonDoc = JSON.parse(s);

Additionally, file a bug report with the author of the program or library that emits malformed JSON.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • Still no luck, am running in on chrome debugger and am still getting syntax error! try copy the string and run it on the chrome console, this is amazing!! – gath Aug 12 '11 at 13:05
  • @gath Feel free to ask a new question about the malformed JSON (include a link to http://pastebin.com/ if it's longer than, say, 20 lines) if you don't find the problem yourself. Also feel free to slap the author of that malformed JSON. – phihag Aug 12 '11 at 13:09
  • @philag, replaced the external double quotes with single quotes worked well. JSON.parse(s.replace(/^"|"$/g,"'")). Thanks lots. – gath Aug 12 '11 at 14:11
1

you should probably remove the outer quotes from your string...

mystring = mystring.replace(/^"|"$/g,'')
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
1

1.This should be your JSON format otherwise, it WILL NOT be parsed properly by JSON.parse

[
        {
            "pk": 1,
            "model": "pms.category",
            "fields": {
                "name": "Rent",
                "add_date": "2011-07-28 01:33:21",
                "agent": 3,
                "category_type": "I",
                "add_user": 3,
                "desc": "Rent"
            }
        },
        {
            "pk": 2,
            "model": "pms.category",
            "fields": {
                "name": "Deposit Rent",
                "add_date": "2011-07-28 01:33:21",
                "agent": 3,
                "category_type": "I",
                "add_user": 3,
                "desc": "Rent Deposit"
            }
        }
    ]

2.Include json2.js from the github repository inbetween your head tags.

Ashwin Krishnamurthy
  • 3,750
  • 3
  • 27
  • 49