0

I got data from the script tag of the website and i stored it in a variable but i am not able to get the values single by signle as if i display data.description it gives me undefined

Here is the code :

const axios=require('axios');
const cheerio=require('cheerio')
  axios.get('https://www.pakwheels.com/used-cars/lahore/24858').then((res)=>{
    const $=cheerio.load(res.data)
var data

 data=$('.classified-listing').first().children('script').text().toString();
// console.log(data1.description)
console.log(data)
  })

It gives this output on console Here is i console it directly

But if i display with with this

console.log(data1.description)

It show me undefined i need to get a specific chunk of data

Need a specific chunk of data

  • 1
    what is ```data1``` ? You can get description by ```console.log(data.description);``` – Srushti Shah Jan 31 '23 at 13:17
  • mistakely typed data1 – Yousaf Zahid Jan 31 '23 at 13:22
  • 1
    You got a string. It is not an object. If it is JSON, you need to [parse it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)... – epascarello Jan 31 '23 at 13:23
  • getting undefined on data.description – Yousaf Zahid Jan 31 '23 at 13:24
  • You got undefined after you [parsed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) the variable data? `var myObject = JSON.parse(data); console.log(myObject);` – epascarello Jan 31 '23 at 13:24
  • yes i both ways i got an undefined – Yousaf Zahid Jan 31 '23 at 13:27
  • So what does `console.log(myObject);` output? Using my code above? – epascarello Jan 31 '23 at 13:30
  • Going to that url and running this in the console it is working fine parsing all of the JSON script tags in the page. ```(function(){ const jsonScripts = [...document.querySelectorAll('script[type="application/ld+json"]')]; const objs = jsonScripts.map(s => JSON.parse(s.textContent.trim())); console.log(objs.map(o => o.description).join(",")); }());``` – epascarello Jan 31 '23 at 13:57

0 Answers0