Home > Enterprise >  Javascript to fetch json from unordered data
Javascript to fetch json from unordered data

Time:10-06

I have below input code inside script code which comes like a string

enter image description here The output should be below as a JSON object and extract flags and preference object. Need a solution using regex or any other way

flags = { "onFlag" : true, "offFlag : false } Preference = { "onPreference" : true, "offPreference : false }

CodePudding user response:

You can use regex to extract data inside the script tag and then parse content in javascript to generate JSON.

const regex = /<script[^>] >(.*?)<\/script>/gs;
const str = `<script type="text/javascript">
window.__getRoute__=function() {
console.log('hi');
}

window.__LOADED_STATE__ = {
"context": {
    "flags": {"onFlag": true, "offFlag": false},
    "Preference": {"onPreference": true, "offPreference": false}
}
}
</script>`;
const m = regex.exec(str);
const json = new Function('var window={}; '   m[1]   ' return window.__LOADED_STATE__')();

console.log(json.context.flags);
console.log(json.context.Preference);
  • Related