I've been searching for an answer but couldn't find it.
I have a json like this:
followersperdate{
'date2012-08-29': 16823,
'date2012-07-09': 15571,
'date2012-07-07': 15528,
'date2012-06-25': 15237,
'date2012-04-19': 13283,
'date2012-03-16': 12999,
etc.
}
and I want to get the values; but everytime I make the request, I recieve other dates. I don't know how to get the values.
I've tried with jsonpath but didn't work.
This is pretty trivial using DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search". Using this method, you can search a JSON structure, regardless of depth for values. It returns an array with the matches (empty array if no matches were found).
To get acquainted with XPath, check out this valuable resource;
http://www.defiantjs.com/#xpath_evaluator
Check out this fiddle;
http://jsfiddle.net/hbi99/DKuAQ/
var data = {
"date2012-08-29": 16823,
"date2012-07-09": 15571,
"date2012-07-07": 15528,
"date2012-06-25": 15237,
"date2012-04-19": 13283,
"date2012-03-16": 12999
},
res = JSON.search( data, '//*' ),
str = '';
for (var i=0; i<res.length; i++) {
str += res[i] +'<br/>';
}
document.getElementById('output').innerHTML = str;
Related
In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .
I'm pulling my hair now with this. I have this str variable in parent window after getting from child window with JSON.stringify. The group of arrays are a collection of inputs.
var str = {"SHOP1":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\"",
"SHOP2":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\""};
What I did was
for(var i in str) {
console.log(i);
console.log(JSON.parse(str[i]));
}
//the output example:
SHOP1
[["name1",1,"anotherdata1"],["name2",2,"anotherdata2"]]
But it will never detect [["name1",1,"anotherdata1"],["name2",2,"anotherdata2"]] as an array but as string.
Is there any way to make Javascript to detect it as an array? Or is there better suggestion or alternative to this?
The trick is to parse it twice. First to get the string, then second to convert it to the arrays.
var obj = {"SHOP1":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\"",
"SHOP2":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\""};
for (var shopname in obj) {
var shop = obj[shopname];
shop = JSON.parse(JSON.parse(shop));
console.log(shop);
console.log(shop.length);
}
I have an object which looks like this.
{
"class_details":{
"class_1":{student_4":"<name>","student_3":"<name>,student_2":"<name>","student_1":"<name>},
"class_2":{"student_1":"<name>},
"class_0":{student_2":"<name>","student_1":"<name>
}
}
I am trying to use a loop to iterate over the classes but I am not able find a perfect way to do it.
I cant do something like this,
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])
So i am doing this
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log(Object.keys($scope.rounds.class_details)[i])
But here the class details do not come in an order and this matters in my case.
It would be great if there is an alternative similar to
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])
or if there is a simple way to sort the JSON class details.
To get the keys in ascending order do:
var class_details_keys = Object.keys($scope.rounds.class_details);
class_details_keys = class_details_keys.sort(function(a,b) {return (+a.substring(6)) - (+b.substring(6));});
for(int i=0, length = class_details_keys ; i < length;i++)
console.log($scope.rounds.class_details[class_details_keys[i]]);
This will return your classes in ascending order by taking the substring after 'class_' and ordering them. You can't do a simple string comparison since "4" > "10" will return incorrect result.
The simplest way to read data like you're hoping is the following:-
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details["round_" + i]);
This is because you can access an objects property in two ways: -
Allows you to pass a dynamic value in (i.e. the i value)
object["property" + withVariable + "Name"]
Simple, readable way where you know the property.
object.propertyName
First, fix json. NOTE: there are some quotes missing in the original code.
"class_details":{
"class_1":{
"student_4":"<name>",
"student_3":"<name>",
"student_2":"<name>",
"student_1":"<name>"
},
"class_2":{
"student_1":"<name>"
},
"class_0":{
"student_2":"<name>",
"student_1":"<name>"
}
}
Followed to this:
//parse to json. Assume the
//'body' is the json data received
//if there is data in body
if(body){
//parse body
var parsed_body= JSON.parse(body);
//your data
var class_details = parsed_body.class_details;
var class_2_student_1 = parsed_body.class_details.class_2.student_1;
//if you want to print json directly to the front-end,
//then Object Object may be printed out. to prevent this,
//one could use .toString() to convert Object to String.
}
else{}//do something if no data in the body
I have a variable that is created by Flowplayer and available via javascript. If I write the variable to the page directly it just returns 'object Object' so I am assuming this is an array. If I don't know the names of any of the objects inside the array, how can I parse out the data inside?
I know I am missing something really fundamental here, but I don't think I have ever had to get data from an array not knowing what it contains.
Notes:
What I am trying to do is get the onCuePoint caption data embedded
into an RTMP video stream
.valueOf() returns the same thing
Here is the code I am using that returns 'object Object':
streamCallbacks: ['onFI'],
clip:
{
live:true,
provider: 'rtmp',
autoPlay: true,
url:'test1',
onFI:function(clip, info)
{
document.getElementById("onFI").innerHTML += "Data: " + info;
}
}
Thank you
If what you are asking is how you iterate over the contents of an array, you can do so in plain javascript like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// arr[i] is each item of the array
console.log(arr[i]);
}
Just because something is of type Object does not necessarily mean that it's an array. It could also just be a plain object with various properties on it. If you look at the info argument in either the debugger or with console.log(info), you should be able to see what it is.
You need to iterate through your array and get the results one by one, replace your onFI function with this :
onFI:function(clip, info)
{
var data = "";
// For each value in the array
for (var i = 0; i < info.length; i++)
{
// Add it to the data string (each record will be separated by a space)
data += info[i] + ' ';
}
document.getElementById("onFI").innerHTML += "Data: " + data;
}
I am receiving a html form. This works fine when 2 or more elements in array, but when only one element is received I get error users[t] is null in fireBug?
var users = form.elements["uname[]"];
for(t in users) {
dataString += "User: "+users[t].value+"\n"
}
this solved it:
if( typeof users.value === 'string' ) {
users = [ users ];
}
I know this is an old question but I stumbed across it while searching for something else. Anyway, I thought I'd provide another answer for anyone else who stumbled across this.
Rather than checking the type to see if it is an array or not and then optionally encasing the value in a new array, you can use Array.prototype.concat().
Its syntax is
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
where any of those values can be either an array or a single value.
In your specific case, you can start with an empty array and concatenate your form input, which will work whether you get a single value or an array:
var users = [].concat(form.elements["uname[]"]);
or
users = [].concat(users);
You could check if the variable is a string and convert it to an array:
if( typeof users === 'string' ) {
users = [ users ];
}
For iterating arrays for-in should be avoided, that statement is meant to enumerate object properties. You could try using a better loop, something like:
var userCount = users.length;
for (var i = 0; i < userCount; i++) {
dataString += "User: "+users[i].value+"\n"
}
You could also base a test on the length. If the object is single it will return undefined for length.
var userCount = users.length; //Get user count
if ( userCount == undefined ) { //Returned undefined if not an array.
users = [ users ]; //Convert to array
}