How to change JSON into string - javascript

i got a words array in JSON form like:
var words = [];
words.push({word:"I",x:50,y:50});
and i want it to store into a txt file which user can download from the website.
...
var data = JSON.stringify(words);
var file = new Blob([data],{type:'plain/text'});
...
however the output file is like this:
{"word":"Peaceful","x":40,"y":65,"lyric":"lyric"}
but i want it only print out the word "peaceful", i tried to use
var data = JSON.stringify(words.word);
but the output shows undefined.

words is an array, so you have to index it to access the object that you pushed onto it:
var data = JSON.stringify(words[0].word);

If I understand you correctly.
var myWords = [];
(for var i = 0; i < words.length; i++) {
var word = words[i].word;
myWords.push(word);
}
myWords.join(' '); // or myWords.join('\n');

Related

How can I create an array from an input string using JavaScript?

Currently I have a PHP page returning some values. The data is something like this:
08-30-2018, in
08-29-2018, out
08-28-2018, in
08-27-2018, in
How can I create a custom array in Javascript with the values above to be similar as this array below:
var system = [
['08-30-2018', 'in'],
['08-29-2018', 'out'],
['08-28-2018', 'in'],
['08-27-2018', 'in']
];
I have tried array.push, but it does not create an array like above.
What should I do? Can you help me? Thank you!
You can use multi-dimensional arrays in JavaScript
var system = [];
var output = "08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in";
var items = output.split("\n");
for(i=0; i<items.length; i++){
var data = items[i].split(",");
var item = [];
item.push(data[0].trim());
item.push(data[1].trim());
system.push(item);
}
console.log(system);
You could also parse this kind of input using regular expressions:
const input = '08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in';
const regex = /(\d{2}-\d{2}-\d{4}), (in|out)/g;
let system = [];
let match;
while ((match = regex.exec(input)) !== null) {
system.push([match[1], match[2]]);
}

jQuery/JavaScript - Converting CSV to Array

I am trying to to convert a CSV file into a javascript array.
Here is my code:
var segments = {
'Segment_1':'inves_cast',
'Segment_2':'foreged_prod',
'Segment_3':'air_prod',
'Segment_5':'worldwide',
'Segment_6':'structurals'
};
var divisions = {
'Division_1':'structurals',
'Division_2':'airfoils',
'Division_3':'wyman',
'Division_4':'energy',
'Division_5':'fasteners',
'Division_6':'struc_comp',
'Division_7':'mech_hard',
'Division_8':'engine_prod',
'Division_9':'corp',
'Division_10':'aero',
'Division_11':'timet',
'Division_12':'',
'Division_13':'spec_metals',
};
var csv = $.get('/path/to/locations.csv');
console.log(csv);
var locationArray = transformLocationData(csv);
function transformLocationData(obj) {
var lineArray = [];
if(obj && obj.data) {
var text = (data.responseText);
lines = text.split('\n');
for(var line in lines) {
var lineTokens = line.split(',');
lineArray = [
lineTokens[0],
lineTokens[1],
lineTokens[3],
lineTokens[4],
lineTokens[5],
lineTokens[6],
lineTokens[11],
lineTokens[12],
lineTokens[13],
lineTokens[14],
lineTokens[15],
segments['Segment_' + lineTokens[8]],
divisions['Division_' + lineTokens[9]]
];
}
}
console.log(lineArray);
}
So what I am trying to do is us AJAX to get the csv file and then split the "responseText" first by line and Second loop through those lines and split it up by commas and then create an array based on those line numbers.
Here is a picture of the data I am getting back from the AJAX call:
With the last console log ( console.log(lineArray); ) it returns an empty array or really it just returns the data the is in var lineArray = []; which is empty if I populate it with data var lineArray = ["Lexus", "Audi", "BMW"]; It will return that array.
Here is a plunker with all the code: https://plnkr.co/edit/CoZGfr6S9R5LDqR1drzq
I know I am doing something wrong but cant seem to get it. I'm not familiar with doing this kind of thing so any help would be greatly appreciated.
You are replacing lineArray with a new array every time, and you're only logging the array at the end of the loop. Perhaps the CSV has an empty line at the end.
If you're wanting an array of arrays, do this instead:
var lineArray = [];
if(obj && obj.data) {
var text = (data.responseText);
lines = text.split('\n');
for(line in lines) {
var lineTokens = line.split(',');
lineArray.push([
lineTokens[0],
lineTokens[1],
lineTokens[3],
lineTokens[4],
lineTokens[5],
lineTokens[6],
lineTokens[11],
lineTokens[12],
lineTokens[13],
lineTokens[14],
lineTokens[15],
segments['Segment_' + lineTokens[8]],
divisions['Division_' + lineTokens[9]]
]);
}
}
console.log(lineArray);
Update:
In addition, you're not handling the results from the Ajax request properly. This line:
var csv = $.get('/path/to/locations.csv');
...does not return the CSV. Rather, it returns a Promise (sort of...). So you cannot parse csv like that. Rather, wait for the results. Change your code to:
$.get('/path/to/locations.csv').then(function (csv) {
var locationArray = transformLocationData(csv);
}, function (err) {
// Handle errors
});
As #vlaz alluded to, you'll also want to change your loop from for..in to a regular for loop:
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
// ...
}

how to convert array with index value into json in angular js

what is the best way to convert this array in to json in angular js:
here i need to convert this data into json
0:"1800-300-1947"
1:"112"
2:"8529631485"
3:"7299490148"
i have tried var myJsonString =JSON.stringify(data);
but its not working it shows like '[]' in the log
In this code i am getting the value from array and pushed into the another array called data. if i log the data i got the above result. how to convert that into json
here i have added my code for your reference
var data = Array();
for (var i = 0; i < contacts.length; i++) {
var contact = contacts[i].phoneNumbers[j].value;
console.log(contact);
data.push(contact);
}
var myJsonString =JSON.stringify(data);
console.log(myJsonString);
Please refer below code for reference its working.
var contacts = [];
contacts[0] = {"phoneNumbers": ["1800-300-1947"]};
contacts[1] = {"phoneNumbers": ["112"]};
contacts[2] = {"phoneNumbers": ["8529631485"]};
contacts[3] = {"phoneNumbers": ["7299490148"]};
var myJsonString = JSON.stringify(contacts);
console.log(myJsonString);

JSON Data to Javascript Array Undefined

I am trying to get data from a JSON file and use Javascript Code to put it into Google Spreadsheet, I did good with some part of the data but I'm stuck with the other part, where I want to match the User Id and put all the data with it on a same row,
JSON Data:
"m":{"414":{"a":{"0":{"c":38,"p":12812.4},
"4":{"c":35,"p":10559.94},"2":{"c":43,"p":35811.63},
"6":{"c":48,"p":45530}},"d":{"0":{"c":55,"p":5477.06225},
"4":{"c":694,"p":106649.473},"2":{"c":1844,"p":716733.50775000011},
"6":{"c":605,"p":324152.5875}},"i":{"0":{"c":0,"p":0},
"4":{"c":0,"p":0},"2":{"c":0,"p":0},"6":{"c":542,"p":19893.93}}},
"404":{"a":{"0":{"c":15,"p":916.182},"4":{"c":50,"p":12357},
"2":{"c":530,"p":390825.27},"6":{"c":58,"p":4841.55}},
"d":{"0":{"c":10,"p":3145.8},"4":{"c":770,"p":141876.12},
"2":{"c":4854,"p":2173966.6125000003},
"6":{"c":1973,"p":1145077.425}},"i":{"0":{"c":0,"p":0},
"4":{"c":0,"p":0},"2":{"c":0,"p":0},"6":{"c":594,"p":25444.41}}}},
Javascript:
var testUF = [];
var Uid = Object.getOwnPropertyNames(doc1.m);
for (var lp2 = 0; lp2 < Uid.length; lp2++) {
var Ua1 = doc1.m[lp2].a["0"].p;
var Ua2 = doc1.m[lp2].a["4"].p;
var Ua3 = doc1.m[lp2].a["2"].p;
var Ua4 = doc1.m[lp2].a["6"].p;
var Ud1 = doc1.m[lp2].d["0"].p;
var Ud2 = doc1.m[lp2].d["4"].p;
var Ud3 = doc1.m[lp2].d["2"].p;
var Ud4 = doc1.m[lp2].d["6"].p;
var Ui4 = doc1.m[lp2].i["6"].p;
testUF.push([Uid,Ua1,Ua2,Ua3,Ua4,Ud1,Ud2,Ud3,Ud4,Ui4]);}
I am getting the Array on the Uid while Debugging, but all the other Variables don't get the data it stays Undefined. I want all the other variables to match with the Uid's and stay in the same row. I did the JSON parsing and everything.
I am asking for the first time on stackoverflow, please forgive me if I couldn't state everything properly. Thank you for the help. :)
You're not using the array index for Uid properly.
Change:
var Ua1 = doc1.m[lp2].a["0"].p;
To:
var Ua1 = doc1.m[Uid[lp2]].a["0"].p;

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

Categories