Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the dataset from string?

Tags:

javascript

please help bring an array of data. spring is here:

{"news": [{"img": "http://static2.smi2.net/img/160x120/2212764.jpeg", "title": "Усиление слуха в 2 - 3 раза! Уникальная разработка", "url": "http://news.smi2.ru/newdata/news?ad=681120&bl=81060&ct=adpreview&st=16&in=lJUrBQDHL4CgZAoA", "id": "681120"}]}

I do the following:

var massive = JSON.parse('http://news.smi2.ru/data/js/81060.js');

console.log(massive.news.id);
console.log(massive.news.img);
console.log(massive.news.title);
console.log(massive.news.url);

The result is the following error message:

Uncaught SyntaxError: Unexpected token h

use only the native js

like image 635
stackov8 Avatar asked Jan 08 '23 19:01

stackov8


2 Answers

You try to parse an url and not a json. You can pass the respone you get and parse it using JSON.parse:

var massive = JSON.parse('{"news": [{"img": "http://static1.smi2.net/img/160x120/2269036.jpeg", "title": "Украинские власти и Саакашвили прокомментировали убийство Немцова", "url": "http://news.smi2.ru/newdata/news?ad=696406&bl=81060&ct=adpreview&st=16&in=uU6IBQAiL4BWoAoA", "id": "696406"}]}');


console.log(massive.news[0].id);//outputs 696406

To clear it up you can make an request to the url you want for example using an ajax call:

 $.ajax({
  url: "http://news.smi2.ru/data/js/81060.js",
  dataType : "json"
}).done(function(res) {
    console.log(res.news[0].id);//outputs 696463
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 54
Alex Char Avatar answered Jan 17 '23 17:01

Alex Char


You cannot parse Json from url .If you need data from URI do send an ajax call for that :- //Simple javascript example.

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     var massive = JSON.parse(xmlhttp.responseText);

console.log(massive.news[0].id);
console.log(massive.news[0].img);
console.log(massive.news[0].title);
console.log(massive.news[0].url);
    }
}
xmlhttp.open("GET","http://news.smi2.ru/data/js/81060.js",true);
xmlhttp.send();
like image 36
squiroid Avatar answered Jan 17 '23 19:01

squiroid