-2

console.log(JSON.stringify($('.btn').attr('data-obj')))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-info user_action" data-action="edit_faqs" data-obj="{SysID:2,Artist:Json Mras,Song:I'm yours}" data-toggle="modal " data-target="#SongsModal
  "><i class="fa fa-edit "></i> Edit</button>

I found this but this is a little different in my case.

When I tried using JSON.stringify on the data I can see in the dev tools

//I want I'm Yours
"{\"Song\":\"I"

The data is stored in my database and I get it in ajax request and I want to use JSON.stringify to it because I will put it as a data-* on a button which will then be used when I click the button. On button click I want to use JSON.parse so I can iterate over it.

How to escape all special characters in JSON.stringify and JSON.parse

Error is:

Uncaught SyntaxError: Unexpected end of JSON input

That points to the JSON.stringify

enter image description here

Added a snippet but it didnt recreate problem so I added an image

Database:

enter image description here

Update:

I get the data from ajax request. After getting the data I use data_array = JSON.stringify(data[i]); then apply the data as data-obj='" + data_array + "'

Manlapig
  • 33
  • 9
  • 1
    Sorry, but I can't believe you. If you do `JSON.stringify("I want I'm Yours")`, you get the string `"I want I'm Yours"` (with double quotes), not `{\"Song\":\"I"`. JavaScript won't invent the word "Song", so the input is _clearly_ not what you say it is. If you have JSON-compatible data, running it through `stringify` and then `parse` is perfectly safe. The problem of the linked question was he started with bad JSON, then tried to run `parse` on it. – Amadan Aug 30 '18 at 04:55
  • Can you show more code? I doubt`I want I'm Yours` became `"{\"Song\":\"I"` just through JSON.stringify – 95faf8e76605e973 Aug 30 '18 at 04:56
  • Also, there is no way to get "Unexpected end of JSON input" from `JSON.stringify`, only from `JSON.parse` – Amadan Aug 30 '18 at 04:59
  • I will show what it looks like in dev give me a minute – Manlapig Aug 30 '18 at 04:59
  • @Amadan I added an snippet but it didnt recreate so I added images instead – Manlapig Aug 30 '18 at 05:11
  • You are not going to be able to stringify that because it is invalid JSON ... try to change the data-obj to ;`{ "SysID": 2, "Artist": "Json Mras", "Song": "I 'm yours"}` – 95faf8e76605e973 Aug 30 '18 at 05:19
  • @emineminems the data is from database after getting it from ajax I apply JSON.stringify to it so I can put it in button as data attribute. Your suggestion Im thinking about changing `'` before applying sa data-attribute Im still working on it – Manlapig Aug 30 '18 at 05:21
  • Also, for next time, please be very careful to give us exact information. In your question, `//I want I'm Yours` cannot correspond to `"{\"Song\":\"I"`; the content you showed in your code snippet `data-obj="{SysID:2,Artist:Json Mras,Song:I'm yours}"` is very different from what is shown in the image you lated posted from your console. It is pretty much impossible to answer questions based on wrong data, and in the extreme case it could get your question closed, with no answers. – Amadan Aug 30 '18 at 05:41

1 Answers1

7

That's not a problem with JSON, it's a problem with your misuse of HTML.

You inserted a raw string into a HTML attribute, probably from a template, possibly by doing something like

<button data-obj="<?php echo json_encode($data); ?>">

Or possibly in JavaScript

container.innerHTML = '<button data-obj="' + JSON.stringify(data) + '">';

so your quotes end up clashing with HTML's. You need to change your quotes into HTML entities; the minimum is changing double quotes " into &quot; if you are using double quotes around the HTML attribute (the most common scenario).

You have not told us how you insert the content into the HTML, so I can't tell you how to do it until you do clarify.

EDIT: Apparently you are building HTML in JavaScript by concatenation. In that case, the solution I showed would work:

container.innerHTML = '<button data-obj="' + data_array.replace(/"/g, '&quot;') + '">';

Or, if you're using single quotes to enclose the attribute (not commonly done, but certainly an option), you would need to change those to &apos; instead:

container.innerHTML = "<button data-obj='" + data_array.replace(/'/g, '&apos;') + "'>";

However, given that it's JavaScript we're talking about, and it can work with DOM, and DOM knows what's what... there's many other solutions. The most primitive one is to work with DOM directly:

let button = document.createElement('button');
button.setAttribute('data-obj', data_array);
container.appendChild(button);

When you do this, JavaScript manipulates the DOM directly, not HTML, so escaping is not needed.

A level above this would be to use a library like jQuery:

$('<button>').data('obj', data_array).appendTo('#container');

A level yet above that would be to use a library that employs data binding, like Angular, React, Vue, Ractive... where you would just set the value on your model, and the document automagically reflects that change.

Changing manually " into &quot; is only needed if you directly manipulate HTML.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 1
    I did the second one. I get the data from ajax request. After getting the data I use `data_array = JSON.stringify(data[i]);` then apply the data as `data-obj='" + data_array + "'` so solution is interchange the quotes? let me try it – Manlapig Aug 30 '18 at 05:25
  • 2
    No; if you're using JavaScript you _can_ change quotes, but it would be better to do it properly with DOM, since DOM will know what to do. Lemme write it out in the answer. – Amadan Aug 30 '18 at 05:26
  • ok i will wait. I tried changing now the first half gets the error. – Manlapig Aug 30 '18 at 05:28
  • I see. Now I get what you mean. I think I will go with the first one. Im actually appending the button in a datatable so Im doing it like that. Let me try it I'll be back shortly – Manlapig Aug 30 '18 at 05:35
  • It did the job Thanks mate happy coding. Explanation is great – Manlapig Aug 30 '18 at 05:41