How to access data in JSON format using javascript - javascript

I'm trying to figure out on how to access data in JSON format and have gone a whole day searching for ways but I still can't find a solution to fit my needs. The closest relative question to my problem is this question but to no avail.
Basically I am retrieving data from $.ajax() which returns in JSON format.
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
My problem is how can I access the elements inside the JSON, say I want to get all values of "nv" or all values of "date" on the second bracket, in javascript? I Am new at things like these so am not familiar with the terminologies, sorry for that.
Below is my code:
var Data = $.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false
}).responseText;
console.log(Data);
url is a variable that is passed inside my function in case you might ask.

Update: See Anthony Grist's comment on your question, I missed the fact that your JSON is invalid. Since he hasn't posted an answer, I'll pick it up.
Your JSON is invalid because you're returning two separate arrays, this one:
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
and this one:
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
You can't do that, because the top level of a JSON document must be one thing (an object or an array).
You could return an object with properties for each array:
{
"vdata":
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
"datedata":
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
}
After parsing (see below), you can access that data like this:
console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"
Or an array with two slots, with each slot having one of your arrays in it:
[
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
]
After parsing (see below), you can access that data like this:
console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"
Personally, I prefer using an object, since then it's clear which array I'm accessing.
Original answer:
jQuery will parse the JSON into an object for you and pass that to the success function, which you can then access just like any other object. In your case, the top level is an array. So:
$.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false,
success: function(data) {
// Use the line from above that suits the way
// you updated your JSON structure
}
});
Side note: async: false is deprecated and will be removed at some point. It's generally not a good idea to do synchronous ajax requests, it tends to lock up the UI of the browser during the request. Instead, just structure your code to continue processing when the success callback is triggered.

If I understand your problem you need to access the same key for all objects in this array.
There is no direct method to do that, you have to iterate through all objects in this array and then find the desired key in each of those objects.
JSON.parse() will convert this string into a Javascript Object (JSON)
var myData = JSON.parse(Data);
for(var i = 0; i < myData.length; i++) {
console.log("This is the nv value of the " + i + " object: " + myData[i].nv);
}

Related

checking json value in javascript

var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);

I'm unable to count the length of an Object

In an ajax call i retrieve a JSON object and count the number of result throught lenght property. But in another code, with same kind of call and little modifications to the server-side script, the length propertu retrieve me alway undefined. Why?
Note that in the developer console the msg is treated like an object (i tink, converted automatically from JSON by ajax), not such an array.
$.ajax({
url : 'richiediListaVideo.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (msg)
{
alert(msg['videos'].length)
},
The object whose "undefined" length is something like
-video
--title
--duration
---tags
---8 "funny"
---1352 "animals"
---13 "Tv"
My goal is to retrieve the tags length, and i wrote msg['video']['tags'].length
This is the stringfied version of "msg"
{"video":{"duration":"5:51","views":"2650","video_id":"512498","rating":"5.00","ratings":"5","title":"Lovely dog", "publish_date":"2013-08-05 16:50:08","tags":{"8":"funny", "54":"lol","75":"Animals","89":"Garden"}}}
Clarification:
Anyway i know how count the number of tags, but the point is that i really want to know why happen this
Anyway i know how count the number of tags
var length=0;
for(var elemy in res['video']['tags']) length++
but the point is that i really want to know why happen this
This is your result:
{"tags":{"8":"funny", "54":"lol","75":"Animals","89":"Garden"}}
That is why you will not be able to use .length.
If you had something like this LOOK AT THE DEMO:
var res =
{ "tags": [
{"8":"funny"},
{"54":"lol"},
{"75":"Animals"},
{"89":"Garden"}
]}
Then .length would work on res['tags'].length.
Anyway i know how count the number of tags
var length=0;
for(var elemy in res['video']['tags']) length++
but the point is that i really want to know why happen this
The reason that this happens is because res['video']['tags'] is an object defined with braces {...} and so it does not possess a length property since it is not a proper array. Proper arrays (one way of defining them is using square braces []) do have a length property.
Note: Named properties (i.e., not indexed by a whole number) are not counted as part of the length of an array, but can also be added to an array. And vice versa--numbered properties can be added to an object.

Javascript: Parse JSON output result

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

Deserializing JavaScript object instance

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
alert("Saving...");
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json"
});
}
}
I am creating Item instances in my app and then saving them to local storage like such:
Item item = new Item();
window.localStorage.setItem("itemKey", JSON.stringify(item));
On another page, or at another time, I am retriving that item from local storage like such:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
Unfortunately, the "save" function does not seem to get reached. In the console window, there is an error that says:
*save_Click
(anonymous function)
onclick*
I have a hunch that the "(anonymous function)" is the console window's way of saying "calling item.save(), but item is an anonymous type, so I am trying to access an anonymous function". My problem is, I'm not sure how to convert "var item" into an Item class instance again. Can someone please show me?
Short answer:
Functions cannot be serialized into JSON.
Explanation:
JSON is a cross-platform serialization scheme based on a subset of JS literal syntax. This being the case, it can only store certain things. Per http://www.json.org/ :
Objects: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Arrays: An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
values: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Functions cannot be serialized into JSON because another non-JS platform would not be able to unserialize and use it. Consider the example in reverse. Say I had a PHP object at my server which contained properties and methods. If I serialized that object with PHP's json_encode() and methods were included in the output, how would my JavaScript ever be able to parse and understand PHP code in the methods, let alone use those methods?
What you are seeing in your resulting JSON is the toString() value of the function on the platform you're using. The JSON serilizer calls toString() on anything being serialized which isn't proper for JSON.
I believe your solution is to stop storing instances in JSON/local storage. Rather, save pertinent data for an instance which you set back to a new instance when you need.
I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.
instead of doing this:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
do something like this:
// get serialized JSON
var itemData = window.localStorage.getItem("itemKey");
//instantiate new Item object
var item = new Item();
// extend item with data
$.extend(item, JSON.parse(itemData));
// this should now work
item.save();
this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.
the $.extend method is a utility method of jquery, but it is trivial to roll your own.
You cant do that, how can javascript possibly knows that item have a save function ? json doesnt allow functions as datas. just read the json spec , you cant save functions.
what you need to do is to create a serialize and deserialize method in the hash you want to stock. that will specifiy what to export and how you can "wake up" an object after parsing the corresponding json string.
You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data
ajaxsend(this.data);
also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use
savestring(JSON.stringify(item.data));
which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:
var item = new Item;
item.data = JSON.parse(getjsonstring());
Disclaimer
Not a full time time J.S. Developer, answer may have some minor bugs:
Long Boring Explanation
As mentioned by #JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.
Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.
Short & quick Answer
Since you already encapsulate the data members of your object into a single field,
you may want to try something like this:
// create J.S. object from prototype
Item item = new Item();
// assign values as you app. logic requires
item.data.name = "John Doe";
item.data.description = "Cool developer, office ladies, love him";
// encoded item into a JSON style string, not stored yet
var encodedItem = JSON.stringify(item.data)
// store string as a JSON string
window.localStorage.setItem("itemKey", encodedItem);
// do several stuff
// recover item from storage as JSON encoded string
var encodedItem = window.localStorage.getItem("itemKey");
// transform into J.S. object
item.data = JSON.parse(encodedItem);
// do other stuff
Cheers.

javascript array mistake

I used to create an array in js
var data = new Array();
data['id'] = self.iframeFields.id.val();
data['name'] = self.iframeFields.name.val();
data['location'] = self.iframeFields.location.val();
data['about'] = self.iframeFields.about.val();
data['company'] = self.iframeFields.company.val();
data['website'] = self.iframeFields.website.val();
but passing var data returns null value
but data['id'] return value.
What did I do wrong?
EDIT:
After nrabinowitz's answer, i was using
if ($.isArray( data )){
ajax({
url: myurl,
data: {
method: "updateProfile",
data: data
},
normalizeJSON: true,
success: function( response ){
// Check to see if the request was successful.
if (response.success){
alert(response);
} else if (onError){
// The call was not successful - call the error function.
alert(response);
}
}
});
}
as it is an object not an array,
it was not returning nothing,
Removing
if ($.isArray( data )){
}
solves the issue.
In Javascript, you want an object, not an array:
var data = {};
data['id'] = self.iframeFields.id.val();
// etc...
You're expecting the array to work like an associative array in PHP, but Javascript arrays don't work that way. I'm assuming you're setting these values by key, and then trying to iterate through the array with something like a for loop - but while you can set values by key, because in Javascript an array is just another object, these values won't be available in standard array iteration, and the length of the array will still be 0.
EDIT: You note that you're using jQuery's .ajax() function to post the data to the server. The .ajax() method expects an object containing key/value pairs, and sends them to the server as a GET or POST parameters. So in your case, if you're using an object as I describe above, your server will receive the parameters "id", "name", etc in the $_POST array - not a "data" parameter.
I suspect, though I haven't tested this, that using var data = new Array(); wouldn't work at all, because of the way jQuery serializes the data passed to .ajax() - even though an array is also an object, jQuery checks if it's an array and treats it differently:
If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()
[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]
So it wouldn't use the key/value pairs you set at all - you would be passing an empty array and no parameters would be passed to the server.
So the right approach here:
Use var data = {};
On the server, look for $_POST['id'], $_POST['name'], etc.
You're using the array like a regular object. You're augmenting the array with additional properties, but the array itself is still empty (you should have an array.length === 0, hence the null). Try changing
var data = new Array();
to
var data = {};
and see what you get.

Categories

Resources