0

I'm currently trying to parse a JSON from a data attribute but I'm getting an error:

Uncaught SyntaxError: Unexpected token � in JSON at position 0

This is my code:

jQuery( document ).ready( function ( $ ) {
 let variations = $( "span" ).data( "variations" );

 $( JSON.parse( variations ) ).each( function ( index, variation ) {
  console.log( variation );
 } );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-variations='["\ud83d\udc36","\ud83d\udc31"]'></span>

I don't get it. I'm printing the JSON in PHP with this function but I'm stuck in my head here:

<span data-variations='<?= esc_html( json_encode( $variations ) ) ?>'></span>
Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
  • So, what's the contents of `variations`? – Cerbrus Mar 04 '20 at 15:04
  • When a string starts with '{' or '[', then jQuery.parseJSON is used to parse it; it must follow valid JSON syntax including quoted property names. A string not parseable as a JavaScript value is not converted. -- Looks like jQuery already parses it for you, don't need to `JSON.parse` again. – Walk Mar 04 '20 at 15:05
  • @Zeljka well in this case it **is** interpreted (by jQuery) as JSON. – Pointy Mar 04 '20 at 15:06
  • @Zeljka `["\ud83d\udc36","\ud83d\udc31"]` is a valid JSON. – Walk Mar 04 '20 at 15:08
  • @Zeljka: No, that's not what's happening there. It _is_ a valid JSON string, and as such, it's parsed as a JOSN string. – Cerbrus Mar 04 '20 at 15:12

2 Answers2

3

You are having this issue because variations already has the parsed value, as said in the doc :

When a string starts with '{' or '[', then jQuery.parseJSON is used to parse it

jQuery( document ).ready( function ( $ ) {
 let variations = $( "span" ).data( "variations" );

 $( variations ).each( function ( index, variation ) {
  console.log( variation );
 } );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-variations='["\ud83d\udc36","\ud83d\udc31"]'></span>
Seblor
  • 6,947
  • 1
  • 25
  • 46
  • 1
    Note that this jQuery behaviour is different to the *native* [`dataset` property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset) – Quentin Mar 04 '20 at 15:07
  • Assuming it's valid JSON. This will return a string: `data-data="{'test':1}"` – Cerbrus Mar 04 '20 at 15:10
1

jQuery notices that the value of the data- attribute is valid JSON, so you get a parsed object from the .data("variations") call. There's no need to parse it yourself.

Pointy
  • 405,095
  • 59
  • 585
  • 614