how can I parse json with multiple lines - javascript

I have the following JSON:
[{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}]
I need to extract all "phoneNumber" using a js function.
I'm testing from using html and my function is not so good:
function getNumbers(strJSON)
{
strJSON = "[{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557704\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557705\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557706\",\"returnCode\":\"0\"}]";
var len = strJSON.length;
var begin_index = strJSON.indexOf("returnCode") - 2;
var last_index = len - 1;
var string_toSplit = strJSON.substring(begin_index, last_index);
var string_splitted = string_toSplit.split("{");
var out="";
alert(strJSON);
alert("string_splitted");
alert(string_splitted);
for ( var i = 0; i < string_splitted.length; i++)
{
if (string_splitted[i].charAt(string_splitted[i].length - 1) === ",")
{
string_splitted[i] = string_splitted[i].slice(0, -1);
}
var json = "{" + string_splitted[i];
var obj = JSON.parse(json);
if (i == string_splitted.length)
{
out = out + obj.phoneNumber;
}
else
{
out = out + obj.phoneNumber + ",";
}
}
return out;
}

For modern browsers you can use the .map() method
var j = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phones = j.map(function(item){return item.phoneNumber});
Update
After seeing your code (do not try to manually split/parse the json string.. use the JSON.parse method) you should use
function getNumbers(strJSON)
{
var myJson = JSON.parse( strJSON );
return myJson.map(function( item ){ return item.phoneNumber}).join(',');
}

Update: An even better way:
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
return obj.map(x => x.phoneNumber).join(", ")
}
Original Post:
A straight forward method is to just iterate over every object in the array and take the values out individually.
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phoneNumbers = [];
for (var i = 0; i < info.length; i++)
{
phoneNumbers.push(info[i].phoneNumber);
}
console.log(phoneNumbers);
http://jsfiddle.net/hX69r/
UPDATE:
http://jsfiddle.net/hX69r/1/
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoString = JSON.stringify(info); //this just turns the object array 'info' into a string
var numbers = getNumbers(infoString);
console.log(numbers);
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
var phoneNumbers = [];
for (var i = 0; i < obj.length; i++)
{
phoneNumbers.push(obj[i].phoneNumber);
}
return phoneNumbers.join(", ");
}
Additional Update:
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoSingle = {"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"};
console.log(info.length); // prints 4; so you know it has the []
console.log(infoSingle.length); // prints undefined; so you know it doesn't have []

Do not try to re-invent the wheel.
There are many ways to parse JSON already:
Use JSON.parse.
Use jQuery.parseJSON

Related

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

Javascript, consolidate array elements

I'm stuck of finding a way to consolidate array elements.
so my array is in format of [id1:port1,id2:port2,id1:port3,id2:port4,id5:port5...] where each element has 2 portions. The id portion is not unique. what I try to consolidate is to create a new array will have data like [id1#port1:port3,id2#port2:port4,id5#port5]
I tried code below but it didn't get me too far. can any guru help me out?
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var newArray1 = orinString.split(",");
var newArray2 = orinString.split(",");
var newArray3 = [];
for (x=0; x<=newArray1.length-1; x++) {
for (y=0; y<= newArray2.length-1; y++) {
if ((newArray1[x].split(":")[0] == newArray2[y].split(":")[0]) && (newArray1[x].split(":")[1] != newArray2[y].split(":")[1])) {
newArray3.push(newArray1[x].split(":")[0] +"#"+ newArray1[x].split(":")[1]);
}
}
}
for (z=0; z<=newArray3.length; z++) {
gs.log("show me the result " +newArray3[z]);
}
is it that you want:
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var arr1 = orinString.split(",");
var temp= "";
var newStr = "";
arr1.sort();
for(i=0; i< arr1.length; i++) {
var item = arr1[i].split(':');
if(item[0] !== temp || temp === "") {
newStr += "," + item[0] + "#" + item[1];
} else {
newStr += ":"+item[1];
}
temp = item[0];
}
console.log(newStr.substring(1));
A typical way to solve a problem like this is
Convert them into workable values
Populate some kind of lookup table
Output the results of this lookup table
For example
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var idsAndPorts = orinString.split(",");
// Populate a key lookup
var hashTable = {};
idsAndPorts.forEach(function(s) {
var splitValue = s.split(':');
var key = splitValue[0];
var value = splitValue[1];
if(hashTable[key]) {
hashTable[key].push(value);
} else {
hashTable[key] = [value];
}
});
// Now convert it back into an array again
var finalArray = [];
for(var k in hashTable) {
finalArray.push(k + '#' + hashTable[k].join(','));
}
// View the results
finalArray.forEach(function(f) {
console.log(f);
})
This does not guarantee the final array will be sorted, but you can sort it yourself if you wish.

Parsing Json Array Object in specific format in javascript

My JSON is:
var json = '{"name":"GeoFence","coordinate":[[1,2],[3,4],[5,6]]}',
obj = JSON.parse(json);
alert(obj.coordinate);
But i need to set the values of coordinates as follows:
var myTrip=[new google.maps.LatLng(1,2),new google.maps.LatLng(3,4),new google.maps.LatLng(5,6)];
Traverse the coordinates and create a new object for each, and add that to myTrip:
var myTrip = [];
for(var i=0; i < obj.coordinate.length; i++) {
myTrip.push(new google.maps.LatLng(obj.coordinate[i][0],obj.coordinate[i][1]))
}
How about this:
var json = '{"name":"GeoFence","coordinate":[[1,2],[3,4],[5,6]]}',
var obj = JSON.parse(json);
var myTrip = [];
for (var i = 0; i < obj.coordinate.length; i++) {
myTrip[i] = new google.maps.LatLng(obj.coordinate[i][0], obj.coordinate[i][1]);
}
You need to iterate over the collection of the coordinates:
var myTrip = getCoordinate ();
var getCoordinate = function(){
var ret = [];
for(var i = 0, length = coordinate.length; i < length; i++){
ret.push(new google.maps.LatLng(coordinate[i][0], coordinate[i][1]))
}
return ret;
}

Arrays Splice Pop Shift Read

I create an array like so
var membersList = $('#chatbox_members' , avacweb_chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers = [];
for(var i =0;i<membersList.length;i++){
var name = $(membersList[i]).text().replace("#","");
onlineUsers.push(name);
}
alert(onlineUsers);
listedUsers would come out something like so [Mr.EasyBB,Tonight,Tomorrow,Gone];
Question is if I use a two for loops one outside a setInterval and one inside to compare-
var membersList = $('#chatbox_members' , _chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers= [];
for(var i =0;i<membersList.length;i++){
var name = $(membersList[i]).text().replace("#","");
onlineUsers.push(name);
}
var int = setInterval(function() {
var newMember = ('#chatbox_members' , _chat.doc.body).find('li');
for(var i =0;i<newMember.length;i++){
var name = $(newMember[i]).text().replace("#","");
offLineUsers.push(name);
}
Which then would get:
onlineUsers = [Mr.EasyBB,Tonight,Tomorrow,Gone];
offLineUsers = [Mr.EasyBB,Tonight];
So to get the offline users I want to basically replace onlineUsers with offLineUsers which then should return Tomorrow,Gone . Though I know that an object doesn't have the function to replace so how would I go about this?
I don't think the splice function would work since you need to have parameters, and pop or shift are beginning and end of array.
for(var i = 0 ; i < offLineUsers.length ; i++)
{
for(var j = 0 ; j < onlineUsers.length ; j++)
{
if(onlineUsers[j] == offLineUsers[i])
{
onlineUsers.splice(j,1);
}
}
}
Try this snippet.
If I have understand well, maybe that helps:
function bus_dup() {
for(var i = 0; i < offLineUsers.length; i++) {
onLineUsers.splice(onLineUsers.indexOf(offLineUsers[i]),1);
}
offLineUsers = [];
}
This should do what you are looking for on a modern browser, using array.filter
var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];
function discord(online, offline) {
return online.filter(function (element) {
return offline.indexOf(element) === -1;
});
}
console.log(discord(onlineUsers, offLineUsers));
Output
["Tomorrow", "Gone"]
On jsfiddle
If you want the difference regardless of the order of attributes passed to the function then you could do this.
var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];
function difference(array1, array2) {
var a = array1.filter(function (element) {
return array2.indexOf(element) === -1;
});
var b = array2.filter(function (element) {
return array1.indexOf(element) === -1;
});
return a.concat(b);
}
console.log(difference(onlineUsers, offLineUsers));
console.log(difference(offLineUsers, onlineUsers));
Output
["Tomorrow", "Gone"] 
["Tomorrow", "Gone"] 
On jsfiddle

Make a JavaScript array from URL

I need to make a Javascript array from URL, eg:
turn this:
http://maps.google.com/maps/api/staticmap?center=Baker Street 221b, London&size=450x450&markers=Baker Street 221b, London&sensor=false
Into something like:
array['center'] = Baker Street 221b, London
array['size'] = 450x450
// and so on...
I need to make this serializaion/unserialization work both ways (url to array and array to the part of the url). Are there some built-in functions that do this?
Thanks in advance!
URL to array: (adapted from my answer here)
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if(!pairs[i])
continue;
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
Array to URL:
function ArrayToURL(array) {
var pairs = [];
for (var key in array)
if (array.hasOwnProperty(key))
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(array[key]));
return pairs.join('&');
}
the above function URLToArray is not working when url string has elem[]=23&elem[]=56..
see below the adapted function... hope it is working - not 100% tested
function URLToArray(url) {
var request = {};
var arr = [];
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
//check we have an array here - add array numeric indexes so the key elem[] is not identical.
if(endsWith(decodeURIComponent(pair[0]), '[]') ) {
var arrName = decodeURIComponent(pair[0]).substring(0, decodeURIComponent(pair[0]).length - 2);
if(!(arrName in arr)) {
arr.push(arrName);
arr[arrName] = [];
}
arr[arrName].push(decodeURIComponent(pair[1]));
request[arrName] = arr[arrName];
} else {
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
return request;
}
where endWith is taken from here
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
/**
* (C)VIOLONIX inc.
* Parser for make multidim array from
* foo[]=any&foo[]=boy, or foo[0][kids]=any&foo[1][kids]=boy
* result: foo=[[any],[boy]] or foo=[kids:[any],kids:[boy]]
*/
var URLToArray = function(url){
function parse_mdim(name, val, data){
let params = name.match(/(\[\])|(\[.+?\])/g);
if(!params)params = new Array();
let tg_id = name.split('[')[0];
if(!(tg_id in data)) data[tg_id] = [];
var prev_data = data[tg_id];
for(var i=0;i<params.length;i++){
if(params[i]!='[]'){
let tparam = params[i].match(/\[(.+)\]/i)[1];
if(!(tparam in prev_data)) prev_data[tparam] = [];
prev_data = prev_data[tparam];
}else{
prev_data.push([]);
prev_data = prev_data[prev_data.length-1];
}
}
prev_data.push(val);
}
var request = {};
var arr = [];
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if(decodeURIComponent(pair[0]).indexOf('[')!=-1)
parse_mdim(decodeURIComponent(pair[0]), decodeURIComponent(pair[1]), request);
else
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//To-do here check array and simplifity it: if parameter end with one index in array replace it by value [0]
return request;
}
There's the query-object jQuery plugin for that

Categories