Converting innerHTML content back to JSON - javascript

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.

Related

JavaScript loop through JSON data and print in html

I'm new to JavaScript and I'm trying to figure out how-to loop through JSON and print each selected value in HTML. My solution below does everything I want except print "all" rows of the JSON data. It only prints the last one. I've been researching on StackOverflow and elsewhere, but I'm not finding the solution. Sorry if this is a redundant question and thank you for your help!
//Fetch JSON from URL
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
//https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
var index;
var obj = JSON.parse(songData);
for (index = 0; index < obj.length; ++index) {
var student_name = obj[index]['name'];
var student_email = obj[index]['email'];
var song_name = obj[index]['song'];
var song_url = obj[index]['url'];
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
}
});
Inside your for loop you are reassigning your elements' content in every Iteration. It means that you fill your elements with the First item of the Array on the First time you run the for, but the Second time you run It, you replace the elements' content with the Second item of the Array. So you get only the Last Item Data.
To solve this problema, you should "increment" your element's content on each Iteration, instead of replace it. To achieve that, you replace the Lines like
document.getElementById("studentName").innerHTML = '<br>'+student_name;
With
document.getElementById("studentName").innerHTML += '<br>'+student_name;
The += operator does a concatenation on strings
Becasue you set string for elements, don't add string.
Replace from:
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
To:
document.getElementById("studentName").innerHTML += '<br>'+student_name;
document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
document.getElementById("songTitle").innerHTML += '<br>'+song_name;
document.getElementById("songURL").innerHTML += '<br>'+song_url;

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

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

converting plain text into json

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

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