简体   繁体   中英

javascript - parse key value json inside html comment

I have an html page with a single-line javascript comment as follows:

// {"key1":"value1"}, {"key2":"value2"}, {"key3":"value3"} 
<b> Sample Text </b>

I want to retrieve all the key value pairs in the comment and place them in javascript maps. How would I parse it using js/jquery? I am terrible at regexes so any help would be appreciated. If it helps, The comment will always be only the first line in the html.

EDIT:

If it makes the job easier, I could also work with -

/* {"key1":"value1"}, {"key2":"value2"}, {"key3":"value3"} */ 
<b> Sample Text </b>

Instead of writing the javascript to the top of the HTML, write it inside a script element like so:

<!-- HTML -->
<head>
<script type="text/javascript">
var x = { "key1": "value1", "key2": "value2", "key3": "value3" } ;
</script>
</head>
<!-- REST OF HTML -->

You should have access to x with your data like any other javascript object.

You could use the jQuery function parseJSON

like:

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

you could then write that value to your html

{"(\\w+?)":"(\\w+?)"}

That will grab you the key and value. Key is in group 1, value in group 2.

For Javascript, raynjamin has pointed out you'll need the /g modifier to match all instances of the key-value pairs.

Play with the regex here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM