1

I'm trying to send JSON data to server using angular, But getting JSON.parse error in firefox and Unexpected token in chrome.

It works sometime and throws error sometime.

I consider it is because of the timestamp I'm using to create some keys.

{
    "genericformfieldId": "1",
    "userId": "2",
    "formData": {
        "_1443551400000": [
            {
                "mValue": "HARYANA",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443637800000": [
            {
                "mValue": "CHHATTISGARH",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443810600000": [
            {
                "mValue": "sac",
                "type": "SingleLineText",
                "name": "departureFrom"
            }
        ]
    }
}

Please suggest.

Adding code for posting data

$http({
    method: 'POST',
    url:    Url, 
    headers: { "Content-Type": "application/json" }, 
    data: formData
    })
.success( function( response, status, headers, config ) {
    console.log( response );
    if( response ) {                    
        deferred.resolve( response );
    }
})
.error( function( response, status, headers, config ) {  
    deferred.reject( null );
});
zion
  • 391
  • 5
  • 22

2 Answers2

1

If you JSON.parse an object the "Unexpected token o" is thrown simply because you are trying to parse object.toString(), which is [object Object]. Try to JSON.parse('[object Object]'); ;)

This should work for you

var data = '{
    "genericformfieldId": "1",
    "userId": "2",
    "formData": {
        "_1443551400000": [
            {
                "mValue": "HARYANA",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443637800000": [
            {
                "mValue": "CHHATTISGARH",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443810600000": [
            {
                "mValue": "sac",
                "type": "SingleLineText",
                "name": "departureFrom"
            }
        ]
    }
}';
JSON.parse(data);

This answer https://stackoverflow.com/a/12719860/1868660 explains Unexpected token ILLEGAL(…) issue

Community
  • 1
  • 1
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
0

You must clean input json.

Check this:

https://jsfiddle.net/am190cv5/

Here's the source:

var s = '{"genericformfieldId": "1","userId": "2","formData": {"_1443551400000": [{"mValue": "HARYANA","type": "DropDown","name": "selectState"}],"_1443637800000": [{"mValue": "CHHATTISGARH","type": "DropDown","name": "selectState"}],"_1443810600000": [{"mValue": "sac","type": "SingleLineText","name": "departureFrom"}]}}';

var result = JSON.parse(s);
console.log(result);

Open the console and look the result.

MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
Maciej Osytek
  • 36
  • 1
  • 4