Stop changing Order In json parse - javascript

this is basic string response :
response = "[{"prefixtodomid":"Sat17Dec2016103310GMT","todo_title":"task 3 changed","is_done_todo":false,"todo_subtitle_field":"\u00a0","prefix_pro_due_date":"","multicheckbox":false,"project_file_list":""},{"prefixtodomid":"Sat17Dec2016103313GMT","todo_title":"ce","is_done_todo":false,"todo_subtitle_field":"\u00a0","prefix_pro_due_date":"","multicheckbox":false,"project_file_list":""},{"prefixtodomid":"Sat17Dec2016103318GMT","todo_title":"dewdw","is_done_todo":false,"todo_subtitle_field":"\u00a0","prefix_pro_due_date":"","multicheckbox":false,"project_file_list":""},{"prefixtodomid":"Sat17Dec2016103321GMT","todo_title":"task 4","is_done_todo":false,"todo_subtitle_field":"\u00a0","prefix_pro_due_date":"","multicheckbox":false,"project_file_list":""},{"prefixtodomid":"Sat17Dec2016181953GMT","todo_title":"task 5","is_done_todo":false,"todo_subtitle_field":"\u00a0","prefix_pro_due_date":"","multicheckbox":false,"project_file_list":{"43":"http:\/\/example\/intra\/wp-content\/uploads\/2016\/11\/1project.png","26":"http:\/\/example\/intra\/wp-content\/uploads\/2016\/11\/2016--\u2039-Le-Blog-OSD-\u2014-WordPress_437.png"}},{"prefixtodomid":"Sat17Dec2016181957GMT","todo_title":"cewcwcwecw","todo_subtitle_field":"\u00a0","project_file_list":{"26":"http:\/\/example\/intra\/wp-content\/uploads\/2016\/11\/2016-10-16-15_26_04-Unyson-\u2039-Le-Blog-OSD-\u2014-WordPress_437.png"}}]"
i parsed it to json like :
var obj = jQuery.parseJSON( response );
now i am looping through this :
for (var i = 0; i<Object.keys(obj).length; i++) {
(function(index){
var haveimage = obj[i].project_file_list;
if(haveimage){
// other logic
}
})(i); // pass the value of i
}
here haveimage is showing image always in order of id of image , even if we change order in response string , parseJSON method just change order by id again , is there any solution to overcome this ?
if not is there anything else i can use instead of parseJSON ?
Thank you :)

An object is an unordered set of name/value pairs.
You can use array to maintain the order:
[
{
"43":"http:\/\/example\/intra\/wp-content\/uploads\/2016\/11\/1project.png"
},
{
"26":"http:\/\/example\/intra\/wp-content\/uploads\/2016\/11\/2016--\u2039-Le-Blog-OSD-\u2014-WordPress_437.png"
}
]

Related

Add an array to a json object in extjs

I wish to have an attribute called idField in my json object. Now this attribute is either an array if it contains multiple elements or just an object if it contains one element. I wish to create such an attribute from the data in an extjs store. In essence if the store contains just one element I need to insert this idField 'object' in the json object otherwise I need to insert an 'array' called idField in the json object. Please advise as to how to do that.
EDIT:
My store has 2 columns namely 'name' and 'type' in its data. What I wish is that if it contains just one element then my object should look like this:
{
...
idField : {
name : ...
type : ...
}
}
If my store contains 2 rows then my object should look like this :
{
...
idField : [
{
name : ...
type : ...
},
{
name : ...
type : ...
}
]
}
Also I have to INSERT this idField attribute inside the object. There is no currect idField attribute yet in the object.
EDIT 2:
I received this object in the console when I wrote console.log(Ext.getStore("My_store_name").data)
To get the data from the EXT JS store
var data = Ext.getStore("Your_Store_Name").data
In my snippet below I am assuming that you like to get the values from field name called item.
var data = Ext.getStore("Your_Store_Name").data
//imagine your JSON where you need to store is in variable myJSON
if (data.items.length == 1){
myJSON.idField = {type: 'sometype', name: data.item[0]} }
else if (data.item.length > 1)
{ //make an array of JSON
var list = [];
for(var i = 0; i < data.item.length; i++)
{
list.push({type: 'sometype', name: data.item[i]})
}
myJSON.idField = list; //set the array
}

How to return only value of a field in mongodb

After applying the find operation in mongodb.. i get the following list of documents..
db.users.find(....)
i got:
{ "text" : "Hey" }
{ "text" : "Hi" }
{ "text" : "Hello" }
{ "text" : "yes" }
How can i convert it into
["Hey","Hi","Hello","yes"].
i tried
db.users.find(...).map( function(u) { return "u.text"; } )
but it is giving error!
Not sure what you language implementation is but the basic concept is:
var result = []
db.users.find().forEach(function(u) { result.push(u.text) })
And the returned value to result is:
["Hey","Hi","Hello","yes"]
At first db.users.find(...).map() didn't work because db.users.find(...) doesn't return you a real array.
So you need to convert to array at first.
db.users.find(...).toArray()
Then if you apply map() function will work
db.users.find(...).toArray().map( function(u) { return u.text ; } )
Another simple trick is using .forEach()
This will do the trick
var cursor = db.users.find(...); // returns cursor object which is a pointer to result set
var results = [];
cursor.forEach(
function(row) {
results.push(row.text);
});
results //results will contain the values
Another option is simply to use distinct:
db.users.distinct("first_name");
Would return:
[
"John",
"Jennifer",
...
]
you can use
var u=db.users.find({...},{text:1,_id:0})
while(u.hasNext()){print(u.Next().text);}
The correct answer here is the method .distinct() (docs)
In your case try it like this:
db.users.find(....).distinct('text')
That will return only the values.
best way is :
db.users.distinct("text");
["Hey","Hi","Hello","yes"].
You will get further information regargding this topic here : mongodb distinct

How to parse dynamic json data?

I am using wikipedia API my json response looks like,
"{
"query": {
"normalized": [
{
"from": "bitcoin",
"to": "Bitcoin"
}
],
"pages": {
"28249265": {
"pageid": 28249265,
"ns": 0,
"title": "Bitcoin",
"extract": "<p><b>Bitcoin</b>isapeer-to-peerpaymentsystemintroducedasopensourcesoftwarein2009.Thedigitalcurrencycreatedandlikeacentralbank,
andthishasledtheUSTreasurytocallbitcoinadecentralizedcurrency....</p>"
}
}
}
}"
this response is coming inside XMLHTTPObject ( request.responseText )
I am using eval to convert above string into json object as below,
var jsonObject = eval('(' +req.responseText+ ')');
In the response, pages element will have dynamic number for the key-value pair as shown in above example ( "28249265" )
How can I get extract element from above json object if my pageId is different for different results.
Please note, parsing is not actual problem here,
If Parse it , I can acess extract as,
var data = jsonObject.query.pages.28249265.extract;
In above line 28249265 is dynamic, This will be something different for different query
assuming that u want to traverse all keys in "jsonObject.query.pages".
u can extract it like this:
var pages = jsonObject.query.pages;
for (k in pages) { // here k represents the page no i.e. 28249265
var data = pages[k].extract;
// what u wana do with data here
}
or u may first extract all page data in array.
var datas = [];
var pages = jsonObject.query.pages;
for (k in pages) {
datas.push(pages[k].extract);
}
// what u wana do with data array here
you can archive that using two methods
obj = JSON.parse(json)
OR
obj = $.parseJSON(json);
UPDATE
Try this this
var obj = JSON.parse("your json data string");
//console.log(obj)
jQuery.each(obj.query.pages,function(a,val){
// here you can get data dynamically
var data = val.extract;
alert(val.extract);
});
JSBIN Example
JSBIN

Using Javascript array or JSON for storing returned values from AJAX request for later use

I have an AJAX request to bring me the values of coordinates from the server.
Heres my code:
locationsObj = []; //Somewhere above the AJAX request
//Below is from the success callback of the request
for (var i = 0; i < rowCount; i++) {
var storelatlng = new google.maps.LatLng(
parseFloat(result.storeLat[i]),
parseFloat(result.storeLon[i])
);
locationsObj.push(??);
}
What I want is to be able to store the returned values in an array OR JSON object, but Ive been fiddling around for ages and I cant seem to get it to work. I believe I may be storing them right, but can not get them out of the array/object as I am getting confused with the [i]'s and [0]'s.
Here is my attempt:
locationsObj.push({storelatlng: storelatlng});
As this is in the for loop, I assume it will loop through and add each var storelatlng to the object??? But how do I get the values back out?
this will give you an array of objects like this:
locationsObj = [
{ storelatlng: 'some value' },
{ storelatlng: 'some value' },
{ storelatlng: 'some value' }
];
so you would access it by:
locationsObj[i].storelatlng;

How to read JSON(server response) in Javascript?

I am sending some request on a server and it's reply me this:
{"COLUMNS":["REGISTRATION_DT","USERNAME","PASSWORD","FNAME","LNAME","EMAIL","MOBILE","FACEBOOK_ID"],"DATA":[["March, 17 2012 16:18:00","someuser",somepass,"somename","somesur","someemail",sometel,"someid"]]}
I tried a lot but nothing seems to working for me!
var xml2 = this.responseData;
var xml3 = xml2.getElementsByTagName("data");
Ti.API.log(xml3.FNAME);
For this code I get "null".
Any help would be appreciated!
If you're trying to use JSON format, your problem is that the data within the [...] also needs to be in pairs, and grouped in {...} like here.
For instance,
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
So you might have:
{"COLUMNS": [
{"REGISTRATION_DT" : "19901212", "USERNAME" : "kudos", "PASSWORD" : "tx91!#1", ... },
{"REGISTRATION_DT" : "19940709", "USERNAME" : "jenny", "PASSWORD" : "fxuf#2", ... },
{"REGISTRATION_DT" : "20070110", "USERNAME" : "benji12", "PASSWORD" : "rabbit19", ... }
]
}
If the server is sending you something which you refer to as res, you can just do this to parse it in your Javascript:
var o=JSON.parse(res);
You can then cycle through each instance within columns like follows:
for (var i=0;i<o.COLUMNS.length;i++)
{
var date = o.COLUMNS[i].REGISTRATION_DT; ....
}
see that link. READ JSON RESPONSE
It's perfect.
JSON objects work just like any normal javascript objects or dictionaries
// You can do it this way
var data = this.responseData["DATA"]
// Or this way
var data = this.responseData.DATA
In your case, COLUMNS and data are both arrays, so it looks like you're trying to get the element from data that corresponds to the "FNAME" element in COLUMNS?
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
for(var i=0; i<columns.length; i++){
if(columns[i] == "FNAME"){
Ti.API.log(data[i]);
}
}
EDIT: If you can't change the data on the server end, you can make your own object client side. This also helps if you have to refer to multiple columns (which you probably do).
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
var realData = {};
for(var i=0; i<columns.length; i++){
realData[columns[i]] = data[i];
}
// Now you can access properties directly by name.
Ti.API.log(data.FNAME);
More edit:
My answers only consider the first row in DATA, because I misread originally. I'll leave it up to you to figure out how to process the others.
If you got here trying to find out how to read from [Response object] (as I did) -
this what can help:
- if you use fetch don't forget about res.json() before logging in console
fetch(`http://localhost:3000/data/${hour}`, {
method: 'get'
})
.then(res => {
return res.json()
})
.then((response) => {
console.log('res: ' + JSON.stringify(response))
})
Testing out your code in http://jsonlint.com/, it says that your server's response is not a valid JSON string.
Additionally, I recommend checking out jQuery.parseJSON http://api.jquery.com/jQuery.parseJSON/
Just use JSON.parse(serverResponse)

Categories

Resources