How to add json stringify to javascript string?

My code:

<script>
var res = `
        <a href="#" id="edit-image"
           data-toggle="modal"
           data-target="#modal-edit-image"
           data-photo="`+JSON.stringify(photo)+`" 
        >
            <span class="fa fa-pencil"></span>
        </a>`;                                                 
</script>

      

The result is console.log(photo)

as follows:

Object {id: 5, name: "IMziQFBIxFEFQHdjlg3mGXEVuQnwqZ5rYigX2jlq.jpeg", alt: "dea"}

I want to change it to json string and store it in res variable

I do it like the above code, but if I check an element and I copy the element, as the result:

<a href="#" id="edit-image" data-toggle="modal" data-target="#modal-edit-image" data-photo="{" id":5,"name":"imziqfbixfefqhdjlg3mgxevuqnwqz5ryigx2jlq.jpeg","alt":"dea"}"="">
    <span class="fa fa-pencil"></span>
</a>

      

It seems json stringfy on untidy element

How can I solve it?

+3


source to share


1 answer


JSON.stringify

uses "

as default line separators. Just data-photo

enclose the attribute value in quotation marks '

instead of "

quotation marks:

var res = `
    <a href="#" id="edit-image"
        data-toggle="modal"
        data-target="#modal-edit-image"
        data-photo='${JSON.stringify(photo)}'
    //             ^ here                   ^ and here
    >
        <span class="fa fa-pencil"></span>
    </a>`;

      

Note 1: One of the advantages of using Template Literals is that you can use ${}

syntax instead + ... +

.

Note 2: If the properties of an object photo

can contain a quote '

, as in:

var photo = {id: 5, name: "I'm here.jpg", alt: ""};
//                         ^^^

      



then you have to avoid it like this :

JSON.stringify(photo).replace(/'/g, "&#39;")
//                   ^^^^^^^^^^^^^^^^^^^^^^^ replace all single quotes with their escaped values

      

by following this last method, you can keep the double quotes as in the code in the question, but avoiding the double quotes this time:

var res = `
    <a href="#" id="edit-image"
        data-toggle="modal"
        data-target="#modal-edit-image"
        data-photo="${JSON.stringify(photo).replace(/"/g, "&#34;")}"
    //             ^ here                                          ^ and here
    // use double quotes to surround the value of data-photo and excape " in the result of JSON.stringify
    >
        <span class="fa fa-pencil"></span>
    </a>`;

      

+1


source







All Articles