I have following string
{
"browser": "firefox",
"dateTime": "28_May_2014_03_35_PM"
}
{
"browser": "firefox",
"dateTime": "28_May_2014_03_36_PM"
}
I want to get elements betwen opening { and closing } braces.
It looks quite like a JSON encoded objects, but i see there are some incongruences, Please pay attention at the little edits in you starting string:
JSON.parse('[{"browser": "firefox","dateTime": "28_May_2014_03_35_PM"},{"browser": "firefox","dateTime": "28_May_2014_03_36_PM"}]');
//this will convert your string to an actual javascript object..
EDIT:
If your json in not proper encoded, you'll have to fix here and there offcourse.. you must add
[{ ... }]{}, {} You can accomplish that with this code
assume that var_string will contain your string..
var_string = var_string.replace(/(\r\n|\n|\r)/gm,""); //removing line breaks;
var_string += '[' + var_string + ']'; //adding square brackets
var_string = var_string.replace(/}{/g, "},{"); //adding commas
var_string = JSON.parse(var_string); //parsing object
{ inside ? . "key": "{", for example?Sanjay, with all the disclaimers already offered about using regex, since you did ask what regex could do for you, here is an expression that would match the two tokens in each of your elements. It assumes that each element only has two tokens, so let us know if that is not the case.
{\s*"([^"]*)":\s*"([^"]*)",\s*"([^"]*)":\s*"([^"]*)"
In the demo, look a the Groups in the lower right panel.
What the regex means
The top right panel of the demo has a token-by-token explanation.
How to use the regex
This is probably obvious for you, but here is sample code to retrieve the values (see output in code demo):
<script>
var subject = '{ \
"browser": "firefox", \
"dateTime": "28_May_2014_03_35_PM" \
} \
{ \
"browser": "firefox", \
"dateTime": "28_May_2014_03_36_PM" \
} \
';
var regex = /{\s*"([^"]*)":\s*"([^"]*)",\s*"([^"]*)":\s*"([^"]*)"/g;
var match = regex.exec(subject);
while (match != null) {
document.write("First token name: ",match[1],"<br />");
document.write("First token value: ",match[2],"<br />");
document.write("Second token name: ",match[3],"<br />");
document.write("Second token name: ",match[4],"<br />");
match = regex.exec(subject);
}
</script>
JSON.parse(str)