Bytes
Bytes

Reputation: 721

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

Upvotes: 0

Views: 1028

Answers (4)

AuxTaco
AuxTaco

Reputation: 5181

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>

Upvotes: 2

GibboK
GibboK

Reputation: 73978

You should have a look at JSON functions as

JSON.stringify()

or

JSON.parse()

Note values passed must be valid.

Upvotes: 0

Sathik Khan
Sathik Khan

Reputation: 439

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

  1. JSON
  2. HTML String

Upvotes: 0

Nikola Andreev
Nikola Andreev

Reputation: 634

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 + ']')

Upvotes: 0

Related Questions