Jake Jake - 4 months ago 10
Javascript Question

JamAPI (turns sites into JSON api) javascript code returns "[object Object]"

I've never worked with JSON, and I understand using JamAPI is a roundabout way of collecting this data, but for the moment, it's what I'd like to use for a quick test project.

In http://www.jamapi.xyz/, I have the following entered into the 2 fields, and it works correctly (it returns the text in each paragraph on this URL)

URL: https://theskint.com/
JSON: {"key": [{ "elem": ".entry-content > p:nth-child(n+2)" , "value": "text" }]}


So that works. But in my project, I'm using the javascript code from JamAPI's git page, but it just returns "[object Object]", and not the text like it does in the previous example.

<script>
fetch('http://www.jamapi.xyz', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://theskint.com/',
json_data: '{ "elem": ".entry-content > p:nth-child(n+2)" , "value": "text" }'

})
}).then(function(response) {
return response.json();
}).then(function(json) {
document.body.innerHTML = json;
});
</script>


(Side note, I'm certainly open to suggestions for the "proper" method of retrieving AJAX from another URL without JamAPI but it may be above my level understanding)

Answer

that code results in and error in the browsers developer tools console:

A provided CSS selector was not found on the provided

if you change your json_data to a format as per that sites examples, e.g.

json_data: '{ "title": "title", "whatever": [{"elem": ".entry-content > p:nth-child(n+2)" , "value": "text"}] }'

You actually get a result ...

To use the result however, change

document.body.innerHTML = json;

to

document.body.innerHTML = JSON.stringify(json);

That will set the body to a json string, and wipe out the rest of the page if that's what you're determined to do

Alternatively, as your code is interested in the JSON string, and not the actual data, to avoid the parsing of JSON to object back to JSON your code would now do

fetch('http://www.jamapi.xyz', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      url: 'https://theskint.com/',
      json_data: '{ "elem": ".entry-content > p:nth-child(n+2)" , "value": "text" }'

    })
  }).then(function(response) {
    return response.text(); // returns text instead of parsed JSON
  }).then(function(json) {
    document.body.innerHTML = json;
  });  
Comments