converting plain text into json - javascript

Suppose I have a text file that I want to convert into json file. Precisely, I want to convert each line $line to "$line":"someid" . Is there a proper way to do that using bash script langage or javascript.
For example
I want to
convert
text into
json
would output
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}

You can't do your expected output like that because you will produce a syntax error, but you can put multiple objects in an array instead. Something like this:
HTML
<div id="id">
I want to
convert
text into
json
</div>
JS
var textArr = document.querySelector('#id').innerHTML.split('\n');
function produceJSON(textArr) {
var arr = [];
// we loop from 1 to 1 less than the length because
// the first two elements are empty due to the way the split worked
for (var i = 1, l = text.length - 1; i < l; i++) {
var obj = {};
obj[text[i]] = i;
arr.push(obj);
}
return JSON.stringify(arr);
}
var json = produceJSON(textArr);
DEMO

Related

How to change JSON into string

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');

Converting innerHTML content back to JSON

I have data that I receive from PHP as an array or array, for example: [[1, "<p>hello</p><img src='blah.jpg'/>"], [2, "blah, blah"].....etc] I then display this data in a div. Afterwards, I go through each image in the displayed output and change the src and add attributes. Afterwards, I get the .innerHTML of that div and place it in a variable.
JavaScript
var data = <?php echo $data; ?>;
document.getElementById("info").innerHTML = data;
var images = document.querySelectorAll("img");
for (var i = 0; i < images.length; ++i){
/*Get image path*/
var tempSrc = images[i].src;
var imgName = tempSrc.split("/").pop();
/*Change image path to loading image*/
images[i].src = "../../resources/media/assets/650x450.png";
images[i].setAttribute('data-src', tempSrc);
images[i].setAttribute('data-mobile-src', "/stories/media/images/small-images/" + imgName);
}
var transformedData = document.getElementById("info").innerHTML;
console.log(transformedData);
The problem that I am facing is that I want to parse transformedData back into JSON, but I can't because now transformedData is back to a regular string. How do I make it so that transformedData is back to an array of arrays?
Some notes
var data = <?php echo $data; ?>; data for example looks like this: [[1, "<p>hello</p><img src='blah.jpg'/>"], [2, "blah, blah"].....etc] When I do console.log(typeof(data)) it returns as object So it's already parsed as JSON
JSON.parse() does not work the error I get is: Uncaught SyntaxError: Unexpected token , in JSON at position 1 This is how transformed data looks: 1,<p>blah, blah</p>, 2, <p>blah</p>, etc. So it's not in array format anymore
The first thing you're doing after getting the data is shoving it into #info, which calls Array.toString() on your data and is lossy. Instead, work with the array for as long as you can before sending it out for display. You can create a DOM element for each HTML string in your data, do work on that element, and send the transformed data into a new array.
const data = [
[1, "<p>hello</p><img src='blah.jpg'/>"],
[2, "blah, blah"]
];
const transformedData = data.map(a => {
const div = document.createElement('div'); // whatever #info is
div.innerHTML = a[1];
const images = div.querySelectorAll("img");
for (var i = 0; i < images.length; ++i) {
/*Get image path*/
var tempSrc = images[i].src;
var imgName = tempSrc.split("/").pop();
/*Change image path to loading image*/
images[i].src = "../../resources/media/assets/650x450.png";
images[i].setAttribute('data-src', tempSrc);
images[i].setAttribute('data-mobile-src', "/stories/media/images/small-images/" + imgName);
}
return [a[0], div.innerHTML];
});
document.getElementById("info").innerHTML = transformedData;
console.log(transformedData);
<div id="info"></div>
If you string now looks like this <p>a</p> <p>b</p>, just put some class on your p tags witch you want to collect back in JSON. Then you need to build array of p tags text content, but this array must be string. You can do something like this:
let arr = documents.getElementsByClassName('yourClass')
let strArray = '['
for (let i = 0; i < arr.length - 1; i++) {
strArray += arr[i].textContent + ', '
}
strArray += arr[arr.length - 1].textContent
JSON.parse(strArray + ']')
You format is cannot be parsed as JSON explicitly. Either you have to traverse through loops to format it or If you have control over your php code, assign javascript variables in server itself. You can define two variables
JSON
HTML String
You should have a look at JSON functions as
JSON.stringify()
or
JSON.parse()
Note values passed must be valid.

Decrypt each element of an Array

I've got an array of n string elements encrypted with CryptoJS : [krypt1, krypt2, krypt3, ...]
The keydecrypt is the same for each element.
I try to decrypt each element of the array and return an array of string decrypted elements like this [dekrypt1, dekrypt2, dekrypt3, ...]
My code is:
var urltodecrypt = this.url.chunk;
function decrypteach(x) {
return CryptoJS.AES.decrypt(x.toString(), keydecrypt).toString(CryptoJS.enc.Utf8);
}
var clearfileurl = urltodecrypt.map(decrypteach);
When there is 1 element in the array, everything's fine: it return an array of rightly decrypted string element.
When there is >1 elements, var urltodecrypt give still the right array (verified), but var clearfileurl return an error: Error: Malformed UTF-8 data
What am I missing?
EDIT
Tried on #vector advices a loop over each element function on this model :
var urltodecrypt = this.url.chunk;
var arrayLength = urltodecrypt.length;
for (var i = 0; i < arrayLength; i++) {
var clearfileurl = CryptoJS.AES.decrypt(urltodecrypt.toString(), keydecrypt).toString(CryptoJS.enc.Utf8);
}
console.log (clearfileurl);
Exact same result = 1 element array :ok / >1 elements array: Error: Malformed UTF-8 data
EDIT #2: question close
I just broke my first code (map) into different vars :
x.toString()
CryptoJS.AES.decrypt()
toString(CryptoJS.enc.Utf8)
I relaunched my server : everything's fine now, from 1 element array to +10 elements array.
Just in case, below my (heavy & superstitious...) tested working code:
var urltodecrypt = this.url.chunk;
console.log (urltodecrypt);
function decrypteach(x) {
var stringurl = x.toString();
var bytesfileurl = CryptoJS.AES.decrypt(stringurl, keydecrypt);
var finaldecrypturl = bytesfileurl.toString(CryptoJS.enc.Utf8);
return finaldecrypturl;
}
var clearfileurl = urltodecrypt.map(decrypteach);
console.log (clearfileurl);

JSON rows Extracting issue in JavaScript

I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?
"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.
The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!

how to load two dimensional array in javascript

I have a string containing many lines of the following format:
<word1><101>
<word2><102>
<word3><103>
I know how to load each line into an array cell using this:
var arrayOfStuff = stringOfStuff.split("\n");
But the above makes one array cell per line, I need a two-dimensional array.
Is there a way to do that using similar logic to the above without having to re-read and re-process the array. I know how to do it in two phases, but would rather do it all in one step.
Thanks in advance,
Cliff
It sounds like you're hoping for something like Python's list comprehension (e.g. [line.split(" ") for line in lines.split("\n")]), but Javascript has no such feature. The very simplest way to get the same result in Javascript is to use a loop:
var lines = lines.split("\n");
for (var i = 0; i < lines.length; i++) {
lines[i] = lines[i].split(" ");
// or alternatively, something more complex using regexes:
var match = /<([^>]+)><([^>]+)>/.exec(lines[i]);
lines[i] = [match[1], match[2]];
}
Not really. There are no native javascript functions that return a two-dimensional array.
If you wanted to parse a CSV for example, you can do
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n') // Normalize newlines
// Parse lines and dump them in parsedStuff.
.replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
Running
stringOfStuff = 'foo,bar\n\nbaz,boo,boo'
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n')
.replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
JSON.stringify(parsedStuff);
outputs
[["foo","bar"],[],["baz","boo","boo"]]
You can adjust the /,/ to suite whatever record separator you use.

Categories