Backbone read JSON item and save to model - json

Hi I'm new to Backbone but have to solve a problem.
There is a working webapp - online shop. On the CartView browsers gets a JSON file from /lampy/api/filter.
I need to save it somehow into model because I need some value from it?
How should I do this?
Thanks in advance.

Let's say your JSON object looks like:
{
item1: 'some string',
item2: 'another string',
item3: 'and another'
}
When you say:
to save it somehow into model
I'm assuming you mean instantiate a model with the values of your JSON object. To do this you can simply do:
var myModel = new Backbone.Model(yourJsonObject)
This will just be a plain Backbone Model without any Url so you won't be able to interact with the server with it, but as you said you need some value from it so you can use:
myModel.get('item1') // returns 'some string'

Related

Is there a way to define a to_json handler in GDScript?

I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.

read a lot of file and xml to json in node.js

I am completely noobie in node.js and I am a university researcher.
I have a lot of files in XML and JSON format, I have a lot of folders and files, I need read it and create one standard (in JSON/CSV) and finally loading it in MySQL database, any tips? do you know npm packages for it or completely solutions?
There are many packages for converting xml to json like xmljs, xml2json, etc..
But looks like you need transforming to standard format for inserting into database as well.
I have this problem myself and i wrote camaro for this purpose: convert and transform xml to json
All i have to do is to write an output template that i would like my xml to be converted too using xpath syntax like below
Of course you can just flatten all the attribute you need ; the below is just example of what camaro can do.
const transform = require('camaro')
const fs = require('fs')
const xml = fs.readFileSync('examples/ean.xml', 'utf-8')
const template = {
cache_key: '/HotelListResponse/cacheKey',
hotels: ['//HotelSummary', {
hotel_id: 'hotelId',
name: 'name',
rooms: ['RoomRateDetailsList/RoomRateDetails', {
rates: ['RateInfos/RateInfo', {
currency: 'ChargeableRateInfo/#currencyCode',
non_refundable: 'boolean(nonRefundable = "true")',
price: 'number(ChargeableRateInfo/#total)'
}],
room_name: 'roomDescription',
room_type_id: 'roomTypeCode'
}]
}],
session_id: '/HotelListResponse/customerSessionId'
}
const result = transform(xml, template)
Thanks #tuananh
Is it possible to use attr of a tag as key or value? Some of my data value i have in attr like <name type="sub-name">Hotel name</name> or <hotelName id='12345'>Hotel name </name> it is possible to do in camaro?
And I have doesn't pure data like <name type="sub-name">Hotel <nameHotel>Hilton</nameHotel></name> It is possible to remove tag nameHotel and save it as {name: 'Hotel Hilton'}
Thank you very much

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

Cast JSON to Mongoose Schema to call Schema Method

I've looked at this question (Is there a native feature to convert string based JSON into Mongoose Schema object instance?) and it's related to my question but doesn't do exactly what I'm looking for.
Essentially, I have JSON I've fetched from an Express response and I'd like to cast it to a Mongoose object for the purposes of calling a schema method on the object.
My schema looks something like this:
var BlahSchema = new Schema({
folder: String,
filename: String,
original: String
});
...
// This is the function I wish to cal
BlahSchema.virtual('url').get(function () {
...
});
From what I understand, when I have an object matching BlahSchema, I can call the method via a simple object.url.
I have two questions. First, the JSON I'm retrieving these objects from erases their schema, right? I'm retrieving these from the database via Blah.search(...function(err, blahs)). This all gets encoded into a JSON object which I return via callback(req, res, search_result) where search_result is an object created via search_result.blahs = blahs, etc. Is there any way to preserve this schema across calls? This would be the preferred method.
Second, if the above is not possible, how do I re-cast JSON to schema without using the save() function mentioned in the answer to the question I pose above? I don't want to re-add objects to the database; I just want to use a method defined for that schema.
EDIT: Express is pretty sick. All you have to do is blah(object).method_name, where blah = mongoose.model('blah')
I save a User (Schema) object to redis in plain JSON.
Get the userData (string) and parse it to JSON object:
var user = new User(JSON.parse(userData))
... and you have all the methods of your User schema.

Backbone.js .save() JSON response attribute issue

So my issue is this.
Using backbone to save something in a MYSQL Database.
When I call this.model.save() I am getting a very weird issue.
The model will save the JSON response as an object and will not update the new values instead.
So my attributes in development tools will look something like this.
attributes: Object
0: Object
ID: "4"
Name: "TEST"
Title: "MEOW"
Stuff: "1"
When: "2013-02-14 22:17:14"
The 0 should not be there. I did confirm that the json object is valid so I know that is not the issue here.
It looks like your JSON response is actually an array with a single element, not an object.
The property 0 is created when Backbone calls model.set(response), which in turn copies all keys of the response object to the attributes hash. If an array is passed to set, this is what happens.
You should fix your server to respond with a raw object ({...}) instead of an array ([{...}]). If you're not able to change the server behaviour, you can override Model.parse to unwrap the response on the client:
var Model = Backbone.Model.extend({
parse: function(response) {
return _.isArray(response) ? response[0] : response;
}
});