MikeJ
MikeJ

Reputation: 2437

AngularJS JavaScript Object to Json

I have the following Json I want to POST.

{
"team": {
    "id": "1",
    "teamName": "TeamName",
},
"location": {
    "id": "1",
    "name": "LocationName",
},
"duration": 60
"dateTime": 949417200000,

}

In my AnguarJS controller I need to accept the form data and create this json dynamically to POST to a web service.

I can get it to work fin without nested json, but not when as above.

    var team = {
        "id": "1",
        "teamName": "TeamName",
    };

    var location = {
        "id": "1",
        "name": "Name",
    };

    var entry = {
        "duration": "40",
        "dateTime": "949417200000",
        "team": + "\"{" + team + "}\"",
        "location": + "\"{" + location + "}\""
    };

Team and Location are null when converted as follows;

console.log(angular.toJson(entry));

Upvotes: 0

Views: 48

Answers (1)

Alyson Maia
Alyson Maia

Reputation: 810

I really don't get why are you using "team": + "\"{" + team + "}\"", and "location": + "\"{" + location + "}\"", if you want to get the entire object in a JSON string, why don't yout just do:

var team = {
    "id": "1",
    "teamName": "TeamName",
};

var location = {
    "id": "1",
    "name": "Name",
};

var entry = {
    "duration": "40",
    "dateTime": "949417200000",
    "team": team,
    "location": location
};

console.log( angular.toJson(entry) );

And try not to use location as a variable, because it can cause unwanted results due do window.location property.

Upvotes: 1

Related Questions