A
A
Arris2015-06-15 14:34:01
JavaScript
Arris, 2015-06-15 14:34:01

JSON Object or not Object. Why?

We have a sign

<table id="example">
   <tbody>
            <tr id="rowID" 
data-all='{"id": 1, "name": "name1"}'>
                <td data-id="01">Tiger Nixon</td>
                <td data-id="02">System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
    </tbody>
</table>

And code
$("#example td").bind('click', function(){
        var all = $('#rowID').data('all');
        alert(all);
    });

(JS Fiddle: jsfiddle.net/57b1m5Lz )

If you write Alert it returns [Object object] And if you write Alert it returns '{"id": 01, "name": "name1"}' Yes, I know that 01 is most likely perceived how to write a number in octal s.s. But - who and when so perceives the data? Browser javascript engine? jquery? And at what stage? Cast? Parsing a piece of `JSON`? Experiments show that if you wrap all data-all keys in quotes, there will always be an Object object (in all tested cases). Thank you!
data-all='{"id": 1, "name": "name1"}'

data-all='{"id": 01, "name": "name1"}'






Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Ineshin, 2015-06-15
@Arris

Most likely jQuery does this by catching the exception in JSON.parse. 01 is not a valid number and will break JSON.parse, which means that when catching an exception, jQuery will assume that this is not JSON and will return just a string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question