Yevgen
Yevgen

Reputation: 797

How to pull JSON data on an HTML page

I would like to pull some information from an HTML page that has a script with JSON data in there. The script looks like this:

<script>
window.miPage = new pageInfo();
Details.initialize({
   "firstName":"John",
   "lastName":"Doe",
   "timeFormat":["am","pm"],
   "dateFormat":"M/d/yyyy",
   "locale":"en"
 });
</script>

I'm hoping to be able to pull the lastName value of "Doe" into a variable and use that as part of a jQuery or JS function.

Note, I can't modify the original script above. Thanks!

Upvotes: 0

Views: 80

Answers (1)

hossein
hossein

Reputation: 313

Here's how you can do it with DOM.

for(let script of document.querySelectoAll("script")) {
  if(script.ismyscript) { // a way to find out if it is the one, you can ignore it
    let match = script.innerHTML.match(/^\s*Details\.initialize\((.*)\);$/m);
    if(match) {
      let json = match[1];
      console.log(JSON.parse(json))
    }
  }
}

Upvotes: 1

Related Questions