I'm trying to get a simple value out of my json string. It seems to be harder than I thought. How can I reach for example the 'name' of the first ModuleAction object in the following JSON (the first array is called 'data'):
[
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
Here's my best attempt:
data[0].ModuleActionModuleController[0].id
But I've got the error:
add:93 Uncaught TypeError: Cannot read property '0' of undefined
at Object.success (add:93)
at j (jquery-2.1.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.1.0.min.js:2)
at x (jquery-2.1.0.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-2.1.0.min.js:4)
Any idea what I'm doing wrong? :)
EDIT
Here's the ajax function that returns the data JSON string:
$(function() {
$('#PageModuleId').on('change', function(){
var formData = $('#PageAddForm').serialize();
// POST to server
$.ajax({
type: 'POST',
url: '<?php echo $this->here; ?>',
dataType: 'text',
data: formData,
success: function(data){
console.log(data[0].ModuleActionModuleController[0].ModuleAction.name);
}
});
});
});
How can I reach for example the 'name' of the first ModuleAction
object in the following JSON?
It appears to me that you are just missing the next child element: ModuleActionModuleController.ModuleAction.name
$(document).ready(function() {
var obj = jQuery.parseJSON( '{"ModuleController":{"id":"3"},"ModuleActionModuleController":[{"id":"4","module_action_id":"1","module_controller_id":"3","ModuleAction":{"id":"1","name":"Overzicht","action":"index"}},{"id":"5","module_action_id":"2","module_controller_id":"3","ModuleAction":{"id":"2","name":"Detail","action":"view"}}]}' );
//alert( obj.ModuleActionModuleController[0].ModuleAction.name );
document.body.innerHTML = obj.ModuleActionModuleController[0].ModuleAction.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works for me:
var JSON = {
"data": [
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
};
alert(JSON.data[0].ModuleActionModuleController[0].ModuleAction.id);
Related
I have this J Query code:
$(document).ready(function(){
var $outData = $('#data');
var ajaxUrl = 'url.json';
$.ajax(
{
type: 'GET',
url:ajaxUrl,
success: function (result) {
console.log(result.passwords);
}
})
}
);
JSON file looks like this:
{
"passwords":[
{
"value":"tom",
"count":"432517"
},
{
"value":"anaconda",
"count":"454658"
},
{
"value":"111111",
"count":"148079"
},
What I need to do, is to print out each of these objects to be printed out in an ordered list (for instance it should look like this:
tom 432517
anaconda 454658
111111 148079
So far, nothing I have tried works. Althoug, I can console.log the entire object. Any suggestions?
Example rendering:
var $outData = $('#data');
var ajaxUrl = 'url.json';
$.ajax(
{
type: 'GET',
url:ajaxUrl,
success: function (result) {
result.passwords.forEach(pwd => $outData.append(`<div>${pwd.value} ${pwd.count}</div>`));
}
})
}
);
you can create elements and append to dom when you are done,
const data = {
"passwords": [{
"value": "tom",
"count": "432517"
},
{
"value": "anaconda",
"count": "454658"
},
{
"value": "111111",
"count": "148079"
}
]
}
const ol = document.createElement("ol");
for (const {
value,
count
} of data.passwords) {
const li = document.createElement("li")
li.innerText = `${value} -> ${count}`
ol.appendChild(li)
}
document.querySelector("#root").appendChild(ol)
<div id="root"></div>
I'm trying the example in reactjs tutorial https://facebook.github.io/react/docs/tutorial.html to read the json from server(file). But, my "componentDidMount" is not getting called.
Below is the code:
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this),
cache: false
});
},
getInitialState: function() {
return {data: {}};
},
componentDidMount: function() {
this.loadCommentsFromServer();
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.content.map(function(comment) {
return (
<Comment pageName={comment.xyz} key={comment.id}>
{comment.abc}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
<h2 className="commentpageName">
{this.props.pageName}
</h2>
<p> {this.props.children} </p>
</div>
);
}
});
ReactDOM.render(<CommentBox url="/api/comments" />, document.getElementById('content'));
Please check the way I have initialized the data(data: {})
The "componentDidMount" gets called when the json is of the following type(Just the way in the tutorial):
[ {"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"} ]
But the json format I want is:
{
content: [
{"id": "1", "xyz": "xyz1", "abc": "abc1"},
{"id": "2", "xyz": "xyz2", "abc": "abc2"},
{"id": "3", "xyz": "xyz3", "abc": "abc3"}],
"totalPages":3,
"totalElements":10,
"last":true
}
Let me know in what conditions the componentDidMount doesn't get called. Please help.
In the "Networks" console of chrome developer tools, I don't see the call made to my json file.
When I added logs in my program, I see that getInitialState() gets called first, then render, then the error "Uncaught TypeError: Cannot read property 'data' of null" is shown.
I think your componentDidMount() is not called because your render code inside <CommentList> does not work on first render, because data is empty, and this.props.data.content probably does not exist, therefore your render fails.
What you probably should do is change this:
var commentNodes = this.props.data.content.map(function(comment) {
To this:
var commentNodes = [];
if (this.props.data.content) {
commentNodes = this.props.data.content.map(function(comment) {
...
}
componentDidMount() is always called after the first render (and not in subsequent renders)
i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'
i read many suggestions concerning jsTree/Json/metadat, but I don't found a working solution. I want to get the metadata (e.g. id) if a node is clicked.
1st my Json Data:
[
{
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
},
"metadata":{
"id":"1000000000000000021"
}
}
}
]
2nd JS function which create the tree and should get the clicked id(ajax call and some oracle apex stuff)
function populateTree(pRegionId) {
console.log('---Js Tree---');
$.ajax({
type : 'POST',
async : true,
url : 'wwv_flow.show',
data : {
"p_request" : 'APPLICATION_PROCESS=GET_TREE',
"p_flow_id" : $v('pFlowId'), // app id
"p_flow_step_id" : $v('pFlowStepId'), // page id
"p_instance" : $v('pInstance'), // session id
},
ggg : pRegionId,
success : function (data) {
console.log(data);
var jsonobj = JSON.parse(data);
apex.jQuery("#" + this.ggg).jstree({
"themes" : {
"theme" : "default",
"dots" : false,
"icons" : true
},
"json_data" : {
"data" : [jsonobj]
},
"plugins" : ["themes","json_data", "ui"]
//}).bind("select_node.jstree", function (e, data) { alert(data.rslt.obj.data("jstree").id); });
}).bind("select_node.jstree", function (e, data) {
console.log(data);
});
}
});
}
3rd the object where the id should be (firebug domview):
args [a#1000000000000000301.jstree-clicked #, true, Object { originalEvent=Event click, type= "click", timeStamp=30977664, mehr...}]
inst Object { data={...}, get_settings=function(), _get_settings=function(), mehr...}
rlbk false
rslt Object { obj={...}, e={...}}
e Object { originalEvent=Event click, type="click", timeStamp=30977664, mehr...}
obj jQuery(li.jstree-closed)
as you can see there is no id. So I guess something with the metadata part is messy but i cannt figure out where the mistake is.
Thanks in advance
Mario
Finally I tracked my mistake down. If you can see in the json code from above:
[
{
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
},
"metadata":{
"id":"1000000000000000021"
}
}
}
]
The metadataobject(?) is within the dataobject like the attr, all online validations show me that my jason code is valid. But the metadatas right place is after the data:
[
{
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
}
},
"metadata":{
"id":"1000000000000000021"
}
}
]
And now I get the id with the following js
.bind("select_node.jstree", function (e, data) {
console.log(data.rslt.obj.data("id"));
});
And if you want an id within the li tag put an attr-object bevor the data-object like:
[
{
"attr":{
"id":"1000000000000000021"
},
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
}
},
"metadata":{
"id":"1000000000000000021"
}
}
]
cu soon
mario
I am trying to get backbone.js to load json.
The json loads but i am not sure how to get the items into my collection.
Or maybe that happens automatically and i just can't trace out. scope issue?
//js code
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
Or fix your JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
If you use rest api, try turn off these parameters:
Backbone.emulateHTTP
Backbone.emulateJSON