4

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?

Here's my code.

Parse.Cloud.httpRequest({
    url: 'http://myservicehost.com', 
    headers: {
        'Authorization': 'XXX'
    },
    success: function(httpResponse) {
        console.log("Success!");

        var json = JSON.parse(httpResponse.text);
        var recipes = json.results;

        for(int i=0; i<recipes.length; i++) {
                var Recipe = Parse.Object.extend("Recipe");
                var recipeFromJSON = recipes[i];
                // how do i save recipeFromJSON into Recipe without setting all the fields one by one?
        }
    }
});
TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76

3 Answers3

6

I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.

for(int i=0; i<recipes.length; i++) {
    var recipeFromJSON = recipes[i];
    recipeFromJSON.className = "Recipe";
    var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
    // do stuff with recipeParseObject
}
Immanuel
  • 324
  • 3
  • 9
1

Example from this page https://parse.com/docs/js/guide

var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();

gameScore.save({
  score: 1337,
  playerName: "Sean Plott",
  cheatMode: false
}, {
  success: function(gameScore) {
    // The object was saved successfully.
  },
  error: function(gameScore, error) {
    // The save failed.
    // error is a Parse.Error with an error code and message.
  }
});
Max
  • 2,293
  • 5
  • 32
  • 48
1

IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]

In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.

const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';   
Parse.Object.fromJSON(asJson);
// Without L3 this results into: 
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible 
Sebastian
  • 63
  • 5