Syntax error when using . val() in a JSON

Asked

Viewed 56 times

-2

I’m trying to check a value in JSON to see if it’s null value containing an image link. But when there is a link it returns an error:

Uncaught Error: Syntax error, unrecognized expression:

I’m using it properly?

var cardapiojson = "https://api.sheety.co/1a888dce-0342-4f9a-9bb6-b0e132d4b33f";

    $.getJSON(cardapiojson, function(data) {
    $(data).each( function (index) {
      var itemImage =  data[index]['img'];

      console.log($(itemImage).val());

I know the mistake is in .val() because when I comment on the console.log($(itemImage).val()); the site mounts normally.

  • 2

    And what I hoped to get from $(itemImage).val()?

  • 1

    itemImage is the value and not an element, so the error. just do console.log(itemImage);

  • 1

    To check if it is null, just do if(!itemImage){ // é null }

  • That’s right @Sam. Thanks for the help. I looked elsewhere and everyone had to use . val() to find out if it was null.

  • .val() is to get value form elements

2 answers

1


I’m using it properly?

Not.


The method getJSON reads the JSON file and transforms it into an object or array (array) depending on the file structure, which in its case is an array of objects.

So to analyze each object of this matrix you need an iteration. For the iteration you are using the method each, iterate over a Jquery object ($(data)).

And to access the property img of the iterated object, the this which in this case is making reference to the iterated object.

$(function() {

  var cardapioJson = "https://api.sheety.co/1a888dce-0342-4f9a-9bb6-b0e132d4b33f";

  $.getJSON(cardapioJson, function(data) {
    $(data).each(function(index) {
      if (!this.img) {
        //Comportamento para quando a propriedade img for nula
        console.log('null');
      }
    });
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

-1

As the example on the site.

$(document).ready(function(){
    $.getJSON('https://api.sheety.co/uk-theme-parks', function(data) {
        var template = Handlebars.compile($('#item-template').html())
        $('#items').html(template(data)) //joga o resultado dentro da tag #items
    })
})

...

<div id="items">Loading theme parks...</div>

The #items is an html element, which is receiving the result within it.

Source: https://sheety.co/

  • if(!itemImage){ // é null } that’s all I needed. But thank you for the answer, Fernando!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.