How to access a text file using javascript? - javascript

I am making a jquery ajax call to the following text file:
sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End
The call is working fine. But I really don't know how to access a particular value like lets say, 'China' from the above text file? I am trying tis for the first time. please help..

Here is the parseParams plugin which you can use to split a querystring into an array.
You can use it like this:
var querystring = 'sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End';
var paramsObj = $.parseParams(querystring);
alert(paramsObj.sport); // = Table Tennis

Don't use such file structure. Use JSON instead. i.e:
{
"sport":"Table Tennis",
"groups":false,
"no_groups":"",
"grp_names":[
],
"teams":[
{
"China":6157
},
{
"Finland":6158
},
{
"Sweden":6159
},
{
"Japan":6149
},
{
"Korea":6154
}
],
"Endstr":"End"
}
Then, after you parse it with $.get or $.ajax, you just access:
data.sports
for example.

Here is code to parse your data. It would have been straight forward if you have chosen JSON as return data.
function myParser() {
var str = "sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End";
var arPairs = str.split("&");
var outObj = {};
for (var i=0; i < arPairs.length; i++) {
var arTemp = arPairs[i].split("=");
var key = arTemp[0];
var value = arTemp[1];
if (key === "teams") {
arTemp = value.split("~");
var teamObj = {};
for (var j=0; j < arTemp.length; j++) {
var arTeamData = arTemp[j].split("^");
teamObj[arTeamData[1]] = arTeamData[2];
}
value = teamObj;
}
outObj[key] = value;
}
return outObj;
}
output: Is an array having all your data available. You can refer it as:
var outObj = myParser();
console.log(outObj.sport); // Prints "Table Tennis"
console.log(outObj.teams.china) // Prints china data

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

Combine a base URL and append an ID to the end by each element in multiple arrays

Forgive me, I have not used JavaScript in 10 years and I want to include any details to help me better understand.
I want to fetch data from an external API using Google Scripts into Google Sheets. Instead of fetching all data, I want to only fetch the data that I have defined in an array.
I'm attempting to join a base URL and add an ID for the data I want specifically.
I have the base URL, and a undefined end of the URL:
const urlBase = 'https://website/item?q';
var urlEnd = '';
I've tried to use join(\'=\') for each element of an array.
The Array looks something like this: (I wanted to output it in different sections when I'm fetching the data)
const itemData0 = ['1da94960-5a14-4cb0-bc25-23a07ecbc915','7ecda500-745e-4275-8b4e-b883b0a28139']
const itemData1 = ['60769d56-6fe0-464f-9d6c-d2a1b6ca6e18','a53b9b6e-3671-43fe-9429-08224083bb11']
const priceData0 = ['0080307d-3596-440c-be38-bdded3cbf4cf','5ac84494-465a-424a-b36e-fe22869ba5ec']
...
The URL should end up being: https://website/item?q=1da94960-5a14-4cb0-bc25-23a07ecbc915
Which should give me,
Header: Items 0
Row0: Data1, Data1a (Each Url ID)
...
Header: Items 1
Row0: Data1, Data1a
...
The API endpoint: (Adding, the let i=o; i<array.length; i++ for each array to replace url)
And collecting Data:
function getItemData() {
let urlData = [];
for (let i=0; i<urlEnd.length; i++) {
urlData[i] = [];
urlData[i][0] = urlEnd[i].itemData0;
urlData[i][1] = urlEnd[i].itemData1;
urlData[i][2] = urlEnd[i].priceData0;
urlEnd.forEach("join function")
}
let data = fetchJSON('https://website/item?q=' + urlData);
let range = ssPrivateData.getRange(`A${1 + HEADER_ROWS_COUNT}:E${1 + HEADER_ROWS_COUNT + data.length - 1}`);
let sheetData = [];
for (let i=0; i<data.length; i++) {
sheetData[i] = [];
sheetData[i][0] = data[i].id;
sheetData[i][1] = data[i].name;
sheetData[i][2] = data[i].price;
sheetData[i][3] = data[i].date;
sheetData[i][4] = data[i].lastSale;
}
range.setValues(sheetData);
setLastUpdateDate();
}
function fetchJSON(url) {
try {
var response = UrlFetchApp.fetch(url, { headers: { 'x-api-key': API_KEY }});
var json = response.getContentText();
var data = JSON.parse(json);
return data;
}
catch(err) {
status = err.message;
}
return status;
}
I cannot get the URLs to combine for each of the arrays. I've tried running this script offline to pull random data to test formatting, but I cannot even get the data to input.
UPDATE
What I did was take all the data instead of the specific ID's. and then filtered the the data that wasn't equal to the array defined. Look at one of the answers, I've explained what I did differently.
Sorry the question wasn't easily understood. hopefully my answer below clarifies what I was trying to do. I still don't know how to append a URL and add ID to it. I feel filtering is better as I dont have to query each time for each ID there is. I just do it once, and ignore the id's I don't want.
I filtered the total results instead of appending each ID to a url.
var filtered_items = {
item_data1 : [array 1],
item_data2 : [array 2]
};
let sheetData = [ ['header 1', 'header 2']];
var row_data = [];
for(var set_key in filtered_items) {
row_data = [ set_key, '', '','', '','',];
sheetData.push(row_data);
for (var k in filtered_items[set_key][k] {
for (let i=0; i<data.length; i++) {
if (data[i].id == filtered_items[set_key][k]) {
row_data = [
set_key,
sheetData[i].id;
sheetData[i].name;
sheetData[i].price;
sheetData[i].date;
sheetData[i].lastSale;
];
sheetData.push(row_data);
break;
}
}
}
row_data = ['','','', '','',];
sheetData.push(row_data);
}
....

Get array from json using javascript

Server returns me such object, but i need only array ITEMS.
How can i get it?
I tried array['items'] but the result is undefiend
{
"items": [
{
..
},
{
..
},
{
..
}
],..
,..
}
// JSON string returned from the server
var text = '{"items":[{"name":"itemX" ,"price":15},{"name":"itemY","price":25},{"name":"itemZ","price":20}]}';
// Convert the string returned from the server into a JavaScript object.
var object = JSON.parse(text);
// Accessing a specific property value of an item
console.log(object.items[0].name); //itemX
// Extract 'items' in to a separate array
var itemsArray = object.items;
console.log(itemsArray); //[itemObject, itemObject, itemObject]
If you're getting this as a string:
var json = JSON.parse(my_json_string)
Then,
var keys = Object.keys(json);
var values = [];
for(var i = 0; i < keys.length; i++){
values.push(json[keys[i]]);
}

Replace Element in JSON with a element in a Javascript array

I have this JSON
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
and I have this JSON
{"computers":[{"id":"7bc530","name":"Dell","description":"Dell"},
{"id":"f30ef","name":"HP","description":"HP"},
{"id":"9e6d","name":"Compaq","description":"Compaq"},
{"id":"4d8665a3","name":"Toshiba","description":"Toshiba"},
{"id":"4fe1457","name":"Asus","description":"Asus"},
{"id":"4a18d27","name":"Acer","description":"Acer"}]}
I want to replace the "serial" element in the first JSON with the "Description" in this one. The reason why I need it in one JSON is that I am using a DataTable and I can only pass one JSON in.
I'm not sure how I can do this in Javascript / JQuery?
You can accomplish this without any jQuery by setting up small function:
(see the demo fiddle)
function replaceSerial (data1, data2) {
var descs = {}, computers = data2['computers'], final = data1;
for (var i = 0; i < computers.length; i++ ) {
descs[computers[i]['id']] = computers[i]['description'];
}
for (var i = 0; i < data1.length; i++) {
final[i]['serial'] = descs[data1[i]['serial']];
}
return final;
}
Then just save your two pieces of JSON into variables and invoke the function:
var json1, json2, mergedJson;
json1 = // DATA IN FIRST JSON;
json2 = // DATA IN SECOND JSON;
mergedJson = replaceSerial (json1, json2);
Assuming your first object is called to and the second object is called from
// Iterate over each entry in to
to.forEach(function(value) {
// In each iteration find elements in from where the id is the same
// as the serial of the current value of to
var description = from.computers.filter(function(element){
if (element.id == value.serial) return true;
});
// Copy description of first found object in the description property of
// the current object
value.description = description[0].description;
// Unset serial?
delete value.serial;
});
DEMO

How to convert json to java script array?

I have the json string like,
string js=[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]
And I need to convert this into like the following format using java script.
[['Pini',111],['Yaniv',123],['Yoni',145]]
How to convert the json string into javascript array using javascript function?
I think something like this:
var ret = [];
for (var i = 0; i < js.length; i++) {
ret.push([js[i].Name, js[i].ID]);
}
// ret holds your array of arrays
Or something like:
var ret = $.map(js, function (el, i) {
return [[el.Name, el.ID]];
});
An example of both: http://jsfiddle.net/RNY8M/
You can do like this
JsFiddler Demo of below code
var JSONObject = {"results":[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]};
var Users= [];
$.each(JSONObject.results, function(i, obj)
{
alert(obj.Name);
alert(obj.ID);
Users.push([obj.Name, obj.ID]);
});​
For this kind of transformations I always prefer using UnderscoreJs which is an utility-belt library (mainly for object/array transformations) for Javascript. I think that it provides great functions that make life easier, allowing javascript developers to be more productive and to achieve a better legibility for the resulting code.
Here is the solution with underscore (extended):
var js=[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]
var names = _.pluck(js, 'Name');
var ids = _.pluck(js, 'ID');
var result = _.zip(names, ids)
And you achive the desired result:
[['Pini',111],['Yaniv',123],['Yoni',145]]
Solution in one line with underscorejs:
var result = _.zip(_.pluck(js, 'Name'), _.pluck(js, 'ID'))
Hope it helps!
Here's a solution that will work for a simple object (not deep objects, though.... but I'll leave that for you to implement).
http://jsfiddle.net/eUtkC/
var js = [{
"Name": "Pini",
"ID": "111"},
{
"Name": "Yaniv",
"ID": "123"},
{
"Name": "Yoni",
"ID": "145"}]
function obj2arr(obj) {
var i, key, length = obj.length,
aOutput = [],
aObjValues;
for (i = length - 1; i >= 0; i--) {
aObjValues = [];
for (key in obj[i]) {
if (obj[i].hasOwnProperty(key)) {
aObjValues.push(obj[i][key]);
}
}
aOutput.push(aObjValues);
}
return aOutput;
}
document.write(JSON.stringify(obj2arr(js)))​
EDIT
Here's a version using Array.prototype.map:
http://jsfiddle.net/eUtkC/1/
function obj2arr(obj) {
var key, aOutput = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
aOutput.push(obj[key]);
}
}
return aOutput;
}
document.write(JSON.stringify(js.map(obj2arr)))​
I correct my solution, I hadn't read well the specs (my fault):
var jsonArray = [{"Name":"Pini","ID":"111"}, {"Name":"Yaniv","ID":"123"}, {"Name":"Yoni","ID":"145"}];
var jsonConverted = {};
$(jsonArray).each( function() {
jsonConverted.push([ this.Name, this.ID ]);
});
This solution uses jQuery.

Categories