I've been losing hours over something that might be trivial:
I've got a list of comma-separated e-mail addresses that I want to convert to a specific JSON format, for use with the Mandrill API (https://mandrillapp.com/api/docs/messages.JSON.html)
My string:
var to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me';
What (I think) it needs to be:
[
{"email": "bigbadwolf#grannysplace.com"},
{"email": "hungry#hippos.com"},
{"email": "youtalkin#to.me"}
]
I've got a JSFiddle in which I almost have it I think:
http://jsfiddle.net/5j8Z7/1/
I've been looking into several jQuery plugins, amongst which: http://code.google.com/p/jquery-json
But I keep getting syntax errors.
Another post on SO suggested doing it by hand: JavaScript associative array to JSON
This might be a trivial question, but the Codecadamy documentation of the Mandrill API has been down for some time and there are no decent examples available.
var json = [];
var to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
json.push({"email":toSplit[i]});
}
Try this ES6 Version which has better perform code snippet.
'use strict';
let to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me';
let emailList = to.split(',').map(values => {
return {
email: values.trim(),
}
});
console.log(emailList);
Try changing the loop to this:
var JSON = [];
$(pieces).each(function(index) {
JSON.push({'email': pieces[index]});
});
How about:
var to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me',
obj = [],
parts = to.split(",");
for (var i = 0; i < parts.length; i++) {
obj.push({email:parts[i]});
}
//Logging
for (var i = 0; i < obj.length; i++) {
console.log(obj[i]);
}
Output:
Object {email: "bigbadwolf#grannysplace.com"}
Object {email: "hungry#hippos.com"}
Object {email: "youtalkin#to.me"}
Demo: http://jsfiddle.net/tymeJV/yKPDc/1/
Related
I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array
This might be a question of pure javascript but somehow I cant get this right. I am working on extjs4.2 using sencha architect. I have a json response sent from server as
{
"data": [{
"ExamID": 1,
"ExamName": "Semester-1",
"MaxMarks": 100
}, {
"ExamID": 4,
"ExamName": "Test-1",
"MaxMarks": 10
}, {
"ExamID": 5,
"ExamName": "Test-2",
"MaxMarks": 10
}]
}
what I am looking for is to reconfigure grid using the data of "ExamName" only. So "ExamName" shall be passed as array in reconfigure() function.
I am unable to get "ExamName" in array form. Your help is highly appreciated
var gridStore = Ext.data.StoreManager.get('ClassSemesterStore');
var g = gridStore.load( {params : {ClassID: ClassData }});
var data = g.data;
var length = data.getCount();
var examName = [];
for(var i = 0; i < length; i++){
examName.push(data[i]['ExamName']);
}
it says "Uncaught TypeError: Cannot read property 'ExamName' of undefined"
I think if I understand you correctly, you're trying to have examName be a new array with it's contents being each ExamName in your response data? If so, this should work.
var data = {"data":[{"ExamID":1,"ExamName":"Semester-1","MaxMarks":100},{"ExamID":4,"ExamName":"Test-1","MaxMarks":10},{"ExamID":5,"ExamName":"Test-2","MaxMarks":10}]}
var examName = [];
for(var i = 0; i < data.data.length; i++){
examName.push(data.data[i]['ExamName']);
}
now examName is an Array with "Semester-1", "Test-1", and "Test-2"
Store's data in not an array. It's a Mixed Collection I think. So either use the following:
var examName = [];
for(var i = 0; i < length; i++){
examName.push(data.items[i].data['ExamName']);
}
or better yet get the information from your source like the people suggested.
Another good alternative is Store's collect.
You can do sth like:
gridStore.collect('ExamName')
The error was because of asynchronous nature of store loading:
var g = Store.load({
params : {ClassID: ClassData },
callback : function(records, operation, success){
var Excerpt = []; // start with empty array
Ext.each(records, function(item) {
// add the fields that you want to include
var Obj = {
third_field: item.get('ExamName')
};
Excerpt.push(Obj); // push this to the array
}, this);
console.log(Excerpt);
}
});
So I have an API that returns JSON data
Example JSON:
{
"result":"OK",
"data":[
{
"number":"613-555-5555",
"calls":30
},
{
"number":"613-666-5555",
"calls":100
}
]
}
I am trying to output this using javascript to show the following
[number, calls],[number, calls]
var response = response.data;
var length = response.length;
alert(data[0].number);
alert(data[0].calls);
for (var i = 0; i < data.length; i++) {
var arrayItem = data[i];
document.write(arrayItem);
}
This is simply a question of mapping your data to the desired format:
var final = response.data.map(function(item) {
return [item.number, item.calls];
});
console.log(final);
Here is a demo: http://jsfiddle.net/c8UQg/
EDIT:
I didn't realise you were looking for a string representation (I thought you wanted an array). If that is the case, please disregard the above.
If you like everything the way it is code wise, and just want to fix the error, then I suggest changing
var response = response.data;
to
var data = response.data;
Also, for the sake of debugging, change
document.write(arrayItem);
to
console.log(arrayItem);
http://jsfiddle.net/GptRW/
I wonder how I can separate an array that consists of "123.152323,152.123232" into "123.152323" and "152.123232".
I pick up the string from a rest, the string looks like this.
responseHandler({"items":[{"name":"xxx","location":["xx.xxxxx","xx.xxxxx"]...
function responseHandler(json) {
var markers = new Array();
for (var i = 0; i < json.items.length; i++) {
markers[i] = (json.items[i].location);
}
}
Can I split the location before putting it into an array? I know split() exists but if the string has more information than just location, such as name, city, etc.
Why reinvent the wheel ? It seems like you have a valid json object, Why not simply use JQuery.parseJSON
Modern browser contain native JSON methods (like JSON.parse, JSON.stringify). Use those, or use an external library like this one from google. It makes your life easier (no need for splitting or regex searches and the like):
function responseHandler(json) {
// use native (JSON.parse), json-sans-eval would be: jsonParse(json)
var myJson = JSON.parse(json)
,markers = []
,i = 0
,len = myJson.length;
for (; i < len; i = i+1) {
markers.push(myJson[i].location);
}
return markers;
}
Edit after comment: you are passing a js-object, so JSON-parsing is not necessary.
function responseHandler(json) {
var markers = []
,i = 0
,len = json.length;
for (; i < len; i = i+1) {
markers.push(json.items[i].location);
}
return markers;
}
//for example
var json = {"items":[
{"name":"xxx","location":["xx.xxxxx","xx.xxxxx"]},
{"name":"yyy","location":["yy.yyyyy","yy.yyyyy"]}
]
};
var locations = responseHandler(json);
//=> now locations[0][0] is 'xx.xxxxx', locations[1][0] 'yy.yyyyy'
(May be you should try finding some reading material on the web about javascript basics)
I have this:
(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)
I'm attempting to get the output to look like this:
"coords": [[65.94647177615738, 87.890625],[47.040182144806664, 90],[45.089035564831036, 122.34375]]
Any Idea?
The first result comes back to me as a string, so when i try to assign the first object to an array, the console shows me this:
array is: "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)"
var str = "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)";
str = str.slice(1,-1); // remove outermost parentheses
var arrCoord = str.split(')(');
for (var i=0; i<arrCoord.length; i++) {
var tarr = arrCoord[i].split(", ");
for (var j=0; j<tarr.length; j++) {
tarr[j] = parseFloat(tarr[j]);
}
arrCoord[i] = tarr;
}
// arrCoord is now populated with arrays of numbers
Decided to sort of play code golf. Assuming:
var sample = '(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)';
Then:
var coords = sample
.split(/\(([^)]+)\)/)
.filter(function(v){return v!=""})
.map(function(v){return v.split(/[^0-9\.]+/)})