Backbone JS parse json attribute to a collection's model - json

I'm having trouble parsing a json to a model.
Here is the JSON:
[
{
"name": "Douglas Crockford",
"email": "example#gmail.com",
"_id": "50f5f5d4014e045f000002",
"__v": 0,
"items": [
{
"cena1": "Cena1",
"cena2": "Cena2",
"cena3": Cena3,
"cena4": "Cena4",
"cena5": "Cena5",
"cena6": Cena6,
"_id": "50ee3e782a3d30fe020001"
}
]
}
]
And i need a model to have the 'items' attributes like this:
cena = new Model({
cena1: "Cena1",
cena2: "Cena2",
...
});
What I've tried:
var cenaCollection = new Backbone.Collection.extend({
model: Cenas,
url: '/orders',
parse: function (response) {
return this.model = response.items;
}
});
then I create new instance of the collection and fetch, but i get "response.items" always "undefined" :|
Thanks in advance!

The parse function should return the attributes hash to be set on the model (see the documentation here). So you'll need simply:
parse: function (response) {
return response[0].items;
}

Related

Struggling to bind JSON data - JQuery Datatables

I am struggling to bind the JSON data into a Datatable. This is my Javascript code.
$.ajax({
type: "POST",
data: $('#searchForm').serialize(),
url: "/ReportingItem/Search",
success: function (data) {
$('#searchResults').DataTable({
data: data,
dataSrc: "",
columns: [
{ "data": "ID" },
{ "data": "ItemContent" }
]
});
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
This is my JSON
"[{"ID":"3","ItemContent":"2nd Test"},{"ID":"4","ItemContent":"3rd Test"},{"ID":"9","ItemContent":"eeeeee"},{"ID":"11","ItemContent":"aaaa"}]"
You can see its a flat array. therefore I have used dataSRC="" so it doesn't look for "data" in the JSON
This is the error message I am getting
DataTables warning: table id=searchResults - Requested unknown
parameter 'ID' for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4
Any help on the Syntax would be helpful!
Thanks
Chris
Just add in the data line
$('#searchResults').DataTable({
data: JSON.parse(data),
....
});
JSON.parse
Just you have to check what json objects return in ReportingItem/Search.
as you mention:
"[{"ID":"3","ItemContent":"2nd Test"},{"ID":"4","ItemContent":"3rd Test"},{"ID":"9","ItemContent":"eeeeee"},{"ID":"11","ItemContent":"aaaa"}]"
in most case json format is camel notation format. it means object names start with lowercase. so you should make some changes in WebApiConfig or if its not api in a config which you set : ReportingItem/Search
add this to the method Register:
using System.Web.Mvc;
using System.Web.Routing;
public static void Register(HttpConfiguration config)
{
var Settings = config.Formatters.JsonFormatter.SerializerSettings;
Settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Settings.Formatting = Formatting.Indented;
//... other codes
}
at the end instead of
columns: [
{ "data": "ID" },
{ "data": "ItemContent" }
]
use this:
columns: [
{ "data": "iD" },
{ "data": "itemContent" }
]
hope its done.

get json value object from mongodb

I have formData node that has dynamic jsonObject value in mongodb
{
"_id": {
"$oid": "5a71fea0f36d2848ae4f8f0a"
},
"formData": {
"pages": [
{
"name": "page1",
"questions": [
{
"type": "comment",
"name": "about",
"title": "Please tell us about your main requirements "
}
]
}
]
},
"editorId": "59678e58f36d2842f777bc48",
"datetimeSubmit": "2018/01/15"
}
I write a node API to fetch the data from mongodb, it only display ids, editorI and datetimesubmit nodes, but it ignores the formData(jsondata) field.
const Model = require('./myModel');
module.exports = {
getData: function (callback) {
Model.find({}, (err, jsonObj) => {
callback(null, {
data: jsonObj
})
})
}
}
looks like the model.find() doesn't return jsonObject value?
thanks
got my own question fixed, basically, i should also define the data type as JSON in schema, otherwise, will be ignored.

Nested JSON with objects and arrays, find value

Im building a React app and I have a quite complex JSON file where I need to find and output certain values of an object in an array.
Im trying to output all my people from my JSON, they look something like this:
people: [
{
"id": 1,
"email": "Sincere#april.biz",
"address": [
{
"street": "Kulas Light",
"type": "house",
"attribute": {
"sketch": "sketch.jpg",
"photo": "photo.jpg"
}
},
{
"street": "Lorem Ipsum",
"type": "apartment",
"attribute": {
"sketch": "sketch.jpg",
"photo": "photo.jpg"
}
}
]
}
]
I have no problem to output the email, doing it like so:
var App = React.createClass({
getInitialState: function () {
return {
results: {}
}
},
componentDidMount() {
fetch(REQUEST_URL) // fetch from API, returns JSON
.then(res => res.json())
.then(data => {this.setState(
{ results: data.people}
);
})
},
renderResult : function(key){
return <Result key={key} index={key} details={this.state.results[key]}/>
},
render : function() {
return (
<ul>
{Object.keys(this.state.results).map(this.renderResult)}
</ul>
)
}
});
var Result = React.createClass({
render : function() {
return (
<li>
{this.props.details.email}
<img src="{this.props.details.address.type=house.attribute.photo}"/>
</li>
)
}
});
ReactDOM.render(App, document.querySelector('#app'));
However, now I need to output "photo" but only for "type": "house". I tried this but no luck, well aware that this is way off. Im quite new to handling JSON data and React and Google hasn't helped me even after a few hours of trying to solve this.
The .address property isn't an object but an array of objects so
.type is not available directly on .address:
this.state.results.people.address.type
// .type property doesn't exist on array
Solution:
You can use Array.prototype.filter on .address to obtain an array of objects that have a property type whose value is "house":
var houseAddresses = this.state.results.people.address.filter(function(value){
return value.type === "house";
});
Here, houseAddress will be an array of objects whose type value is 'house".
You can then loop through the array to create the relevant JSX using for, Array#forEach or Array#map. The following example uses Array#map:
const houseImgTags = houseAddresses.map(function(house, index){
return (
<img
src={house.attribute.photo}
key={'house'+index}
/>
);
});
(A key was added here in case there are more than one instance of a house object)
You can simply write.
<img src={this.states.results.address.type==="house"?house.attribute.photo : otherwise_photo}/>
Basically this would compare address.type is house or not,then return the result corresponded.

Use JSON data coming from WebApi in AngularJS application

I get some data from a WebApi, the answer (below the code to get the datas) is in JSON. But I can't access this result from angularJS. The datas look like :
{
"$id": "1",
"result": [
{
"$id": "2",
"name": "Français",
"code": "FR",
"id": 1
},
{
"$id": "3",
"name": "Néerlandais",
"code": "NL",
"id": 2
},
{
"$id": "4",
"name": "English",
"code": "EN",
"id": 3
}
]
}
But I get the error below when I try to display the result :
data.result is undefined
I get the data like this :
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http', dataService]);
function dataService($q, $http) {
return {
initFormCustomer: initFormCustomer
};
function initFormCustomer() {
return $http({
method: 'GET',
url: 'http://localhost:123456/api/forminit/customer/',
headers: {
},
transformResponse: transformCustomer,
cache: true
})
.then(sendResponseData)
.catch(sendGetCustomerError)
}
function sendResponseData(response) {
return response.data;
}
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data.result);
console.log(data.result[0]);
return transformed;
}
function sendGetCustomerError(response) {
return $q.reject('Error retrieving customer(s). (HTTP status: ' + response.status + ')');
}
}
}());
The controller :
(function () {
angular.module('myApp')
.controller('customerController', ['$location', '$scope', 'dataService', CustomerController]);
function CustomerController($location, $scope, dataService) {
var vm = this;
vm.languages = dataService.initFormCustomer();
}
}());
I think the transform function gets a json string that you have to deserialize before using it as an object... try sth like:
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data);
console.log(transformed.result[0]);
return transformed.result;
}
Additionally you may look at the docs https://docs.angularjs.org/api/ng/service/$http . There is some code showing how to append a transform to the default one (that do the deserialization and XSRF checks)

Ember Data One to One Relationship Record Creation Fails

I receive the following error when I use Ember Data to create records from a JSON response. What gives? I am following what the docs state.
Uncaught Error: Assertion Failed: Ember Data expected a number or string to represent the record(s) in the `user` relationship instead it found an object. If this is a polymorphic relationship please specify a `type` key. If this is an embedded relationship please include the `DS.EmbeddedRecordsMixin` and specify the `user` property in your serializer's attrs object.
JSON being parsed:
[
{
"id": 76,
"title": "Title",
"shipped": 0,
"date": "2015-05-21T05:00:00.000Z",
"user": {
"firstName": "First Name",
"lastName": "Last Name",
"email": "hellothere#gmail.com",
"id": 1
}
}
]
Shipment Model:
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
user: DS.belongsTo('user', { async: false })
});
Route:
import Ember from 'ember';
export default Ember.Route.extend({
beforeModel: function() {
if(!localStorage.accessToken) {
this.transitionTo('login');
}
},
model: function() {
var shipmentObjects = [];
var App = this;
Ember.$.getJSON('http://localhost:1337/subscription/1/shipments/upcoming', function(shipments) {
shipments.forEach(function(data) {
var shipment = App.store.push('shipment', data);
shipmentObjects.pushObject(shipment);
});
});
return shipmentObjects;
}
});
You can create a custom serializer, if you can't modify your json response and manage to arrange data in other way
App.MODELNAMESerializer = DS.ActiveModelSerializer.extend({
extract: function(store, type, payload, id, requestType){
var shipments = [];
//CREATE A NEW PAYLOAD THAT EMBER CAN READ
var _payload = { };
return this._super(store, type, _payload, id, requestType);
}
});
Your json should look something like this
{
shipments: [
{
"id": 76,
"title": "Title",
"shipped": 0,
"date": "2015-05-21T05:00:00.000Z",
"user_id": 1,
}
],
"users": [
{
"firstName": "First Name",
"lastName": "Last Name",
"email": "hellothere#gmail.com",
"id": 1
}
]
}
Read the error message. It could hardly be clearer. By default, Ember Data expects an association to be represented by an ID. If the association is instead embedded, you must tell Ember Data that. You'll need something like:
// serializers/shipment.js
export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
user: { embedded: 'always' }
}
});
And remove the {async: false}, since the data is embedded right there.
See http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html.