0

I have anchor element.I want to store and retrive the object in it like this way.

<a  id ="test" data-val="{key1:val1,key1:val1}"> </a>

If I save in this way,while fetching it

$("#test").data('val') it gives me string like

"{key1:val1,key1:val1}".

But I am unable to parse it to json or javascript object again. I have tried using $.parseJSON(),JSON.parse(). But it throwing an error.

How we can achive it without localstorage or sessionstorage o cookie

EDIT :

After calling $("#test").data('val')

I am getting string like this

"{'category_slug' : 'featured','tip_slug':'tip-with-all-cats'}"

If i have use $.parseJSON()or JSON.parse() it throwing an error

Uncaught SyntaxError: Unexpected token
1
  • Note that once you've corrected the format to valid JSON (as pointed out below) jQuery will automatically parse it for you when placing it in the internal data cache, so you don't need to call JSON.parse() on it. See this example: jsfiddle.net/cxznLctj Commented Mar 9, 2016 at 13:10

2 Answers 2

4

That's because it's not valid JSON.

Valid JSON has quoted keys and uses double quotes to delimit strings. Your example doesn't meet these requirements.

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

3 Comments

@RIYAJKHAN My answer still stands. Use double quotes. And make sure your string ends with a }
@RIYAJKHAN single quotes are invalid in json object key.
Thanks @alex. I got it
1

That is not valid JSON, specifically you're missing quotes:

{"key1":"val1","key1":"val1"}

1 Comment

That also looks invalid. You're missing at least a trailing } and the quotes are single quotes instead of double quotes (but the parser might accept it).

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.