How to change name of JSON key? - json

children: [
{
name:'Basic Ext Layouts',
expanded: false,
children:[
{
name:'Absolute',
id:'absolute',
leaf:true,
},{
...
}]
}]
Is it possible to change children to mydata?

Is it possible to change children to mydata?
Yes. Setup treestore's proxy to use reader with root config set to 'mydata':
var store = Ext.create('Ext.data.TreeStore', {
model: 'MyModel',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'mydata' // << this is required
}
},
root: {
myData: [
{
name:'Basic Ext Layouts',
Here is working example.

JSON format is merely a String in javascript's point of view. So you could manipulate the JSON string with associated method.
JSON.
// The original
obj = {
children: [
{
name:'Basic Ext Layouts',
expanded: false,
children:[
{
name:'Absolute',
id:'absolute',
leaf:true,
}]
}]
}
// Transfer the object to a JSON string
var jsonstr = JSON.stringify(obj);
// HERE you do the transform
var new_jsonstr = jsonstr.replace('"children"', '"mydata"');
// You probably want to parse the altered string later
var new_obj = JSON.parse(new_jsonstr);

Related

Json Schema validate reference property on same object

Using JSON Schema 7 to perform validations
Is the below validation possible using json schema.
{
properties : [{name: "a"}, {name: "b"}, {name: "c"}],
rules : [{ prop : ["a","b"] }, { prop : ["a"] }, {prop: ["c"]}]
}
The "prop" property in object is dependent values in properties.
ie only of "properties.name" exists then that value can be added to the "prop" array
Note:
The "properties" array can have any object of type {name : }
"name" can have any possible string, which i don't know beforehand
I have been going through documentation, but can find a answer.
Is this validation not supported in Json Schema yet?
You can't do it with a static JSON schema.
To archive it you would need a dynamic schema validation, but this could be dangerous to code injection from malicious users:
const Ajv = require('ajv')
const ajv = new Ajv({ allErrors: true, jsonPointers: true })
const data = {
properties: [{ name: 'a' }, { name: 'b' }, { name: 'c' }],
rules: [{ prop: ['a', 'b'] }, { prop: ['a', 'zz'] }, { prop: ['c'] }]
}
const validProp = data.properties.map(_ => _.name)
const schema = {
type: 'object',
required: ['properties', 'rules'],
properties: {
properties: {
type: 'array',
items: {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string' }
}
}
},
rules: {
type: 'array',
items: {
type: 'object',
required: ['prop'],
properties: {
prop: {
type: 'array',
uniqueItems: true,
items: {
type: 'string',
enum: validProp // here happen the validation
}
}
}
}
}
}
}
const isValid = ajv.validate(schema, data)
if (!isValid) {
console.log(ajv.errors)
}

How can I pass the data from Django to a Shield UI Grid?

I'm new using Django and Shield UI, what I'm trying to do is trying to get data for a shieldGrid, making a request to get remote data from the server. I have the next code.
this is my .js
$("#id_table_diagnosticos").shieldGrid({
dataSource: {
remote: {
read: {
url: "/atender/ListadoDiagnosticos/",
dataType: "json",
operations: ["sort", "skip", "take"],
data: function (params) {
var odataParams = {};
if (params.sort && params.sort.length) {
odataParams["$orderby"] = window.orderFields[params.sort[0].path].path + (params.sort[0].desc ? " desc" : "");
}
if (params.skip != null) {
odataParams["skip"] = params.skip;
}
if (params.take != null) {
odataParams["top"] = params.take;
}
return odataParams;
}
}
},
schema: {
data: "fields",
total: function (result) {
return result["odata.count"];
},
fields: window.orderFields = {
// "pk": { path: "pk" },
"descripcion": { path: "descripcion" },
"codigo": { path: "codigo" },
}
}
},
paging: true,
sorting: true,
columns: [
// { field: "pk", title: "ID", width: 80 },
{ field: "descripcion", title: "Descripción", width: 180 },
{ field: "codigo", title: "Código", width: 100 },
]
});
});
my model.py is
class ParametrosDiagnosticos(models.Model):
descripcion=models.CharField(max_length=1000)
codigo=models.CharField(max_length=100)
sexo=models.CharField(max_length=10,default='Ambos')
estado=models.CharField(max_length=100, default='Activo')
estado_logico=models.IntegerField(default=1)
and my view.py
def ListadoDiagnosticos(request):
if request.user.is_authenticated:
if request.method=='GET' and request.is_ajax():
objeto=ParametrosDiagnosticos.objects.all()
data = serializers.serialize('json', objeto, fields=('pk','descripcion','codigo'))
return JsonResponse(data,safe=False);
The request to server is doing ok, the problem is that when I return the data, I get the next error on the console of my browser.
shieldui-all.min.js:4 Uncaught TypeError: Cannot read property 'map' of undefined
at e (shieldui-all.min.js:4)
at init.fields (shieldui-all.min.js:5)
at init.process (shieldui-all.min.js:5)
at init._success (shieldui-all.min.js:5)
at e (bundled.js:2)
at Object.z.func.i.success (shieldui-all.min.js:4)
at j (bundled.js:2)
at Object.fireWith [as resolveWith] (bundled.js:2)
at x (bundled.js:5)
at XMLHttpRequest.b (bundled.js:5)
Thank you for your help.
Make sure your Grid's dataSource.schema is configured correctly. Documentation about it can be found here.
For example, if your data returned from the server contains a list of objects, you do not need to set its data property.

build json from multiple links, JavaScript

I have a json objectlike this
{"test": [{"href": "http://sdfsd.fd"}], "test2": [{"href": "http://sdfsd.fd"}]}
What I want to do is interate over all the links in the json, every likn point to another json object. then i want to get the json from the links, and replace the links with that json, so it comes like something like this:
{"test": {somejson}, "test2": {somejson}}
can this be done? right now I tried with a nested for loop, but the loop doesnøt care that the hhtp request hasn't got a response, before continuing in the loop, resulting in nothing is gonna be edited.
EDIT:
my code so far looks like this:
self.buildJSON = function(json) {
var links = [];
for(var post in json){
// console.log(json[post]['_links']);
for(var link in json[post]['_links']){
links.push(json[post]['_links'][link][0]['href']);
}
}
// var regex = /(http[s]?:\/\/)?([^\/\s]+)(.*)/
// for(link in links){
// var match = regex.exec(links[link]);
// var host = match[1]+match[2];
// var path = match[3];
// links[link] = {"host": host, "path": path};
// }
for(link in links){
request(links[link], function(error, response, body){
if (!error && response.statusCode == 200) {
links[link] = body;
}
})
}
console.log(links);
fs.writeFile(self.jsonfile, JSON.stringify(json));
the Json something like this ('_links' is part of a bigger json):
_links: {
self: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts/19"
}
],
collection: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts"
}
],
about: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/types/post"
}
],
author: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/users/1"
}
],
replies: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/comments?post=19"
}
],
version-history: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts/19/revisions"
}
],
wp:featuredmedia: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/media/130"
}
],
wp:attachment: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/media?parent=19"
}
],
wp:term: [
{
taxonomy: "category",
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/categories?post=19"
},
{
taxonomy: "post_tag",
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/tags?post=19"
}
],
curies: [
{
name: "wp",
href: "https://api.w.org/{rel}",
templated: true
}
]
}
You need to parse your JSON first to get the links (maybe put them in an array). (hint: use JSON.stringify() and it becomes a string that you can parse)
Then iterate over each array element and send XHR requests (hint: XMLHttpRequest object). If you want to 'care' for each response, then use xhttp.open(method,url,false) and xhttp.send(). The 'false' will tell that Asynchronous mode is off and so it becomes synchronous. Beware of performance issues now since its synchronous. Read more here
Now create your own JSON object by storing the links in a string and using json.parse(string) to convert it to json

How to read nested JSON structure with a Sencha Touch Data Model?

I've been trying to figure this out all evening but to no avail. I have a JSON structure as follows (coming from another system so I can't change its structure):
{
"parents":{
"parent":[
{
"parentId":1,
"children":{
"child":[
{
"childId":1,
},
{
"childId":2,
}
]
}
},
{
"parentId":2,
"children":{
"child":[
{
"childId":1,
},
{
"childId":2,
}
]
}
}
],
"pageNum":1,
"pageSize":2
}
}
However, I can't figure out what the correct structure for the data models should be. I've tried the following but it does not work. BTW, I can access the parent information. The issue is with accessing the child information. So, I guess there is something wrong with how I've set up the relationship data.
Ext.regModel("ParentModel", {
hasMany: {
model: 'ChildrenModel',
name: 'children.child' // not too sure about this bit
},
fields: [
{name: 'parentId', type: 'string'}
],
proxy: {
type: 'ajax',
url : 'models.json',
reader: {
type: 'json',
root: 'parents.parent' // this works fine
}
}
});
Ext.regModel('ChildrenModel', {
belongsTo: 'ParentModel', // not too sure about this bit
fields: [{name: 'childId', type: 'string'}]
});
with a data store:
Ext.regStore('ParentModelStore', {
model: 'ParentModel',
autoLoad:true
});
I'm using the following template which gets me the parent information, but I can't get the child data from it:
myapp.views.ParentView = Ext.extend(Ext.Panel, {
layout: 'card',
initComponent: function() {
this.list = new Ext.List({
itemTpl: new Ext.XTemplate(
'<tpl for=".">',
'<div>',
'{parentId}', // this works fine
'</div>',
'<tpl for="children.child">', // this doesn't work
{childId}
'</tpl>',
'</tpl>',
),
store: 'ParentStore',
});
this.listpanel = new Ext.Panel({
layout: 'fit',
items: this.list,
});
this.items = this.listpanel;
myapp.views.ParentView.superclass.initComponent.apply(this, arguments);
},
});
Ext.reg('ParentView', myapp.views.ParentView);
What I'm struggling with is the fact that both the "child" and "parent" elements are surrounded by another element, "children" and "parents" respectively.
Any help much appreciated.
Thanks in advance,
Philip
PS If I remove the outer "children" wrapping element and just leave the inner "child" element (and change "children.child" to "child" in the model definition) the code works fine.
PPS I'm answering my own question:
Doh! I forgot to add the "children" element to the ParentModel's fields.
It should be as follows (note: I didn't need to specify the 'hasMany' or 'associations' elements - not too sure why this is or what is the benefit of including them):
Ext.regModel("ParentModel", {
fields: [
{name: 'parentId', type: 'string'},
{name: 'children'} // VERY IMPORTANT TO ADD THIS FIELD
],
proxy: {
type: 'ajax',
url : 'models.json',
reader: {
type: 'json',
root: 'parents.parent' // this works fine
}
}
});
Ext.regModel('ChildrenModel', {
fields: [{name: 'childId', type: 'string'}]
});
The template works fine too:
'<tpl for="children.child">', // this syntax works too.
{childId}
'</tpl>',
Ran into a similar problem recently..I think.
You need to specify the mapping to the data you want in your model.
For example :
Ext.regModel('Album', {
fields: [
{name: 'artist_name', mapping: 'album.artist.name'},
{name: 'artist_token', mapping: 'album.artist.token'},
{name: 'album_name', mapping: 'album.name'},
{name: 'token', mapping: 'album.token'},
{name: 'small_cover_url', mapping: 'album.covers.s'},
{name: 'large_cover_url', mapping: 'album.covers.l'}
]/*,
getGroupString : function(record) {
return record.get('artist.name')[0];
},*/
});
consumes this JSON:
{
"album":{
"covers":{
"l":"http://media.audiobox.fm/images/albums/V3eQTPoJ/l.jpg?1318110127",
"m":"http://media.audiobox.fm/images/albums/V3eQTPoJ/m.jpg?1318110127",
"s":"http://media.audiobox.fm/images/albums/V3eQTPoJ/s.jpg?1318110127"
},
"artist":{
"name":"New Order",
"token":"OyOZqwkN"
},
"name":"(The Best Of)",
"token":"V3eQTPoJ"
}
},
I've added a converter to allow the template access the data in the model consistently regardless if a single object or an array is returned.
Ext.regModel("ParentModel", {
fields: [
{name: 'parentId', type: 'string'},
{name: 'children', convert:
function(value, record) {
if (value.child) {
if (value.child instanceof Array) {
return value.child;
} else {
return [value.child]; // Convert to an Array
}
}
return value.child;
}
}
],
proxy: {
type: 'ajax',
url : 'models.json',
reader: {
type: 'json',
root: 'parents.parent' // this works fine
}
}
});
Note: I don't actually need to define the ChildrenModel. I guess I can get away without defining it as Sencha must be automatically type converting it.

Simple JSON example with senchaTouch

I'm trying to achieve a simple JSON operation:
I want to write on my page a text coming from a file in JSON format.
The file is like this: (data.json)
{
"id": "0",
"name":"myname"
}
The script is getting the JSON:(main.js)
Ext.setup({
onReady: function() {
Ext.regModel('Person', {
fields: [
{name: 'id', type: 'string'},
{name: 'name', type: 'string'}
]
});
//I want the name to be written on the page
var itemTemplate = new Ext.XTemplate(
'<tpl for=".">',
'{name}',
'</tpl>');
// I get and decode the Json from data.json
var jsonStore = new Ext.data.Store({
model: "Person",
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json'
}
},
autoLoad: true
});
// The panel should get the stored Result and display it
var jsonPanel = new Ext.Panel ({
title: "json",
fullscreen: true,
items: [
{
xtype: 'list',
store: jsonStore,
itemTpl:itemTemplate,
}
]
});
}
});
The index.html file calls all the files above and sencha-touch.js and .css.
I just don't manage to see anything written on the page.
If someone can give me a clue about what i am doing wrong it would help a lot.
Try to put your JSON objects in array notation, like this:
[{
"id": "0",
"name":"myname"
}, {
"id": "1",
"name":"myname2"
}]
As far as I can remember (at least that was the case in ST1, I did not try with ST2), the Ajax reader cannot be used to access local files. You need to have your json data delivered through a web server