I just working with JSON data and am playing around with jQuery and Ajax requests. Pretty basic stuff, but here's my problem.
I have a basic data set which I was using for time tracking. I know how to parse the simple JSON data like this:
{
"end" : "1/18/2011",
"start" : "1/18/2011",
"task" : "Code Review",
},
It's the more complicated stuff I'm trying to parse like this where I'm trying to pull the "time" data out.
{
"end" : "1/17/2011",
"start" : "1/17/2011",
"task" : "Exclusive Brands",
"time" : {
"analysis" : 4,
"documentation" : 3,
"meetings" : 2
}
This is the code for the script I've been using to parse the simple data:
$(function() {
$('.load').click(function(){
$.getJSON("data.js",function(data){
$.each(data.timesheet, function(i,data){
var div_data ="<div class='box'>"+data.start+" "+data.task+"</div>";
$(div_data).appendTo("#time-tracking");
});
}
);
return false;
});
});
My question is what's the format to parse the time data, or what's the best way to parse the information nested inside the time element?
Any help will be greatly appreciated.
A JSON string will be parsed into an object. When parsed, the time is the key of one object. You could retrieve the value of this object through the dot operator (.).
data = JSON.parse('{"end":"1/17/2011", "start":"1/17/2011", "task":"Exclusive Brands", "time": {"analysis":4, "documentation":3, "meetings":2 } }')
// => obj
data.time.analysis
// => 4
In your case similarly you could use the data.time.meetings to access your data from remote server.
Unless I am terribly mistaken, since jquery already converted data into a javascript for you, you should be able to access time as if it was a javascript object like so:
var analysis = data.time.analysis;
var documentation = data.time.documentation;
var meetings = data.time.meetings;
etc...
Related
To my understanding, JSON strings were ways to package information to be sent around, much like xml.
This is also what's highly circulated in the stack-exchange questions
eg: What is JSON and why would I use it?
However, a recent bot for a game that I play took json files as "scripts" of actions to perform. In this way, users of the bot were able to customize actions that the bot was expected to perform.
This seemed to violate my mental model of what json's were and what they could accomplish. My current suspicion is that rather than using these "script" json files as packages of information to send, they are instead processed internally by the bot, which then translates our "scripts" into real actions.
Please enlighten me if I've misunderstood what json is.
JSON is just a structure, literally it is "JavaScript Object Notation", http://json.org/.
processed internally by the bot
is basically what is going on.
The json string is parsed into an object, and based on the values of that object the bot reacts. There is no scripting involved in it. However, it is possible that some of the values are literally script in a string, which can be used in JavaScript with eval in order to execute.
I suspect that eval is not being used in that fashion though, and that the bot is simply reading key value pairs to take as instruction for example moveright:5 feet.
Here is a very quick example of taking expected commands in json and then executing them in some sort of process. The implementation is basic, just a proof of concept.
var json = '{ "actions": [ { "speak": "hello world" }, { "color" : "red" } ]}';
var obj = JSON.parse(json);
var i = 0;
var bot = document.querySelector("#bot");
var actions = {
speak : function(text){ bot.innerText = text; },
color : function(c){ bot.style.color = c; }
};
function act(action){
for(var key in action){
var value = action[key];
actions[key](value);
}
if(i <= obj.actions.length)
setTimeout(function(){
act(obj.actions[i++]);
},500);
}
setTimeout(function(){
act(obj.actions[i++]);
},500);
<div id="bot">:)</div>
I have a database with lots of document and i am using field type to define it as a table. I want to populate angularjs ui-grid with the JSON data coming in value. So i have created a view:
function(doc) {
if(doc.type === 'userTable'){
emit(doc._id, {userName:doc.userName,fName:doc.fName});
}
}
When i hit the url http://127.0.0.1:5984/rpt_db/_design/Dsgn_userjson/_view/Vw_userjson/ it gives me :
{"total_rows":1,"offset":0,"rows":[
{"id":"f43a147cd5c961fcfe4e1da1b800013a",
"key":"f43a147cd5c961fcfe4e1da1b800013a",
"value":{"userName":"rp670249","fName":"Ranjeeth"}}
]}
Now in my client code i need to do a loop and make data as JSON.
result.rows.forEach(function(item) {
var temp = { "id": item.value.userName, usrName: item.value.fName};
console.log(temp);
//Update data of grid using temp variable.
});
Is there an easy way so that i can directly use what's coming as part of couchdb JSON output which can be used as is in angular ui-grid.
You can refer column values using json dot notation in the columnDefs. Since your actual values are inside "value". you can create column definition like this,
$scope.myData = {"total_rows":1,"offset":0,"rows":[
{"id":"f43a147cd5c961fcfe4e1da1b800013a",
"key":"f43a147cd5c961fcfe4e1da1b800013a",
"value":{"userName":"rp670249","fName":"Ranjeeth"}}
]}
$scope.gridOptions = {
data : $scope.myData.rows,
columnDefs : [
{name:"id",field:"value.userName"},
{name:"usrName",field:"value.fName"}
]
};
Here's a working plnkr.
http://plnkr.co/edit/juLZeT6I0LOlek4QnMSP?p=preview
I have a json file called data.json containing some data:
[
{
"name" : "toto"
}
]
And the script I wrote to manage it :
var Data = $resource("data.json", {},
{
query: {method:'GET',isArray:true}
});
var data = Data.query(function()
{
var d = data[0];
d.name = "Titi";
d.$save();
});
Everything work before I call $save() on my object. I have this error:
[11:30:24.962] "Error: [$resource:badcfg] Error in resource configuration.
Expected response to contain an object but got an array
I don't really know the problem. I have already read many examples and documentations but this does not seem clearer to me.
Just guessing to help quickly here... You may have several issues, var d = data[0]. data should be from an argument/parameter of the function not the var data which is null until the return result from Data.query changes it. $save should also likely be on the $resource object, not the object in the array. Not an angular person, but guessing that might be the case.
We have an internal API that was specifically built to be used with a new piece of software I'm building that runs on Backbone. The API has a single URL and takes JSON as input to determine what it needs to return. It essentially allows me to build custom queries with JSON that return exactly what I'm looking for.
Thing is this JSON can get pretty verbose and is often 3–4 levels deep, but sometimes may just be a few lines and just 1 level deep.
First question first: How do I send a string of JSON along with the ID when I do a fetch()? Do I have to set these parameters as the model or collection's defaults?
Here is an example of a really simple string to get a specific user's info
{
"which" : "object",
"object" : {
"type" : "customer",
"place" : "store",
"customerID" : "14"
}
}
As others have suggested it will likely be challenging to work with SOAP, but it shouldn't be impossible. Backbone models and collections communicate with the server through the sync operation; you should be able to customize that. I think something along these lines might get the ball rolling (for models):
Backbone.SoapyModel = Backbone.Model.extend({
sync: function(method, model, options) {
// force POST for all SOAP calls
method = 'create';
options = _.extend(options, {
// Setting the data property will send the model's state
// to the server. Add whatever complexity is needed here:
data: JSON.stringify({
"which" : "object",
"object" : model.toJSON()
}),
// Set the request's content type
contentType: 'application/json'
});
// Defer the rest to Backbone
return Backbone.sync.apply(this, [method, model, options]);
}
});
var SoapyModelImpl = Backbone.SoapyModel.extend({
url: '/test'
});
var soapTest = new SoapyModelImpl({
id: 42,
name: 'bob',
address: '12345 W Street Dr',
phone: '867 5304'
});
soapTest.fetch();
I have a rest service for which I am sending the Json data as ["1","2","3"](list of strings) which is working fine in firefox rest client plugin, but while sending the data in application the structure is {"0":"1","1":"2","2":"3"} format, and I am not able to pass the data, how to convert the {"0":"1","1":"2","2":"3"} to ["1","2","3"] so that I can send the data through application, any help would be greatly appreciated.
If the format of the json is { "index" : "value" }, is what I'm seeing in {"0":"1","1":"2","2":"3"}, then we can take advantage of that information and you can do this:
var myObj = {"0":"1","1":"2","2":"3"};
var convertToList = function(object) {
var i = 0;
var list = [];
while(object.hasOwnProperty(i)) { // check if value exists for index i
list.push(object[i]); // add value into list
i++; // increment index
}
return list;
};
var result = convertToList(myObj); // result: ["1", "2", "3"]
See fiddle: http://jsfiddle.net/amyamy86/NzudC/
Use a fake index to "iterate" through the list. Keep in mind that this won't work if there is a break in the indices, can't be this: {"0":"1","2":"3"}
You need to parse out the json back into a javascript object. There are parsing tools in the later iterations of dojo as one of the other contributors already pointed out, however most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is:
var str = your_incoming_json_string,
// here is the line ...
obj = JSON.parse(string);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
For the browsers that don't support JSON.parse() you can implement it using json2.js, but since you are actually using dojo, then dojo.fromJson() is your way to go. Dojo takes care of browser independence for you.
var str = your_incoming_json_string,
// here is the line ...
obj = dojo.fromJson(str);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
If you're using an AMD version of Dojo then you will need to go back to the Dojo documentation and look at dojo/_base/json examples on the dojo.fromJson page.