Search code examples
htmljsonmarkup

How to (re)create JSON records from HTML data attributes


This might be something quite trivial, but I have very little experience in the field so it might as well turn out quite complicated.

Basically, I'm trying to render a bunch of HTML data attributes into their JSON equivalents. For example I have the following HTML markup (I've cut it since it's too long):

    <span class="play-queue play-queue-med-small" data-json=
        "{&quot;id&quot;:
         4276028,
         &quot;selected&quot;:
         false,&quot;type&quot;:
         &quot;track&quot;,&quot;sku&quot;:
         &quot;track-4276028&quot;,&quot;name&quot;:
         &quot;This Is What It Feels Like feat. Trevor   Guthrie&quot;,&quot;trackNumber&quot;:
        2,&quot;active&quot;:true,&quot;mixName&quot;:
        &quot;W&amp;
        W Remix&quot;,&quot;title&quot;:
        &quot;
        This Is What It Feels Like feat. Trevor Guthrie 
        (W&amp;W Remix)&quot;,&quot;slug&quot;:
        &quot
;this-is-what-it-feels-like-feat-trevor-guthrie-w-and-w-remix&quot;,
&quot;isrc&quot;:&quot;
    NLF711303293&quot;,&quot;releaseDate&quot;:
       &quot;2013-04-05&quot;,&quot;publishDate&quot;:&quot;2013-04-05&quot;,&quot;sampleUrl&quot;:&quot;

From this I want to render the data-json attribute into a JSON record looking like:

{
“key1”:”value1”,
“key2”:”value2”,
...
“keyN”:”valueN”
}

Is there any way to do this? Maybe a method (either in C# or in Java), or some workaround?

Thank you a million in advance!


Solution

  • The client side solution would look like:

    JSON.parse(unescape($('span.play-queue').data('json'))) 
    

    The C# equivelent is the HttpUtility.HtmlDecode