0

I have saved JSON in a HTML object attribute like this:

<div data-json='[[30,"https:\/\/www.google.de\/",true],[41,null,null],[42,null,null],[15,null,null]]'>

When i now want to access that via jQuery it fails:

jQuery.parseJSON( jQuery('div').attr( 'data-json' ) );

It seems like the attr method is adding additional backslashes that causes this problem.

Any ideas?

EDIT: Sorry guys the problem isn't that what i've pointed out here. So this question is obsolete. Thanks for your answers.

3
  • not an answer to your solution, but would it be better to render that JSON as a javascript variable rather then in an html attribute? Commented Apr 28, 2017 at 8:11
  • try this JSON.parse( jQuery('div').attr( 'data-json' ) ); Commented Apr 28, 2017 at 8:13
  • Has the same problem with the added backslashes Commented Apr 28, 2017 at 8:18

2 Answers 2

2

I didn't really change anything and it worked just fine. Not sure what your problem was exactly. Maybe the way it was accessed or something else on the page messing it up.

var data = jQuery.parseJSON(
    $('div').attr('data-json')
    );
  
$("#contents").append(data[0][0]);
$("#contents").append("<br>");
$("#contents").append(data[0][1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div data-json='
  [
    [30,"https:\/\/www.google.de\/",true],
    [41,null,null],
    [42,null,null],
    [15,null,null]
  ]
'>

<div id="contents"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering. The problem lies in a other part of the code so this one actually works. My fault ._.
-1

Try to use $('div').data('json') instead of .attr

5 Comments

why not attr()?why data()?
Didn't now that you can access this with .data() ... i thought this was a completely own jquery kind of api for storing information related to objects. Anyway data returns exactly the same output than attr. So this doesn't work ... Im within wordpress so its a pretty old jquery version. Maybe thats the problem.
I think it's somehow related to html5 data attributes but I'm not sure; Also, you don't have to JSON.parse() if you are using .data, isn't this enough to use more convenient method?
can you supply info on you don't have to JSON.parse() if you are using .data,
I've just tried this in browser console. Not sure it's mentioned somewhere in the docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.