HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Extracting JSON from string using regex

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
usingextractingjsonregexfromstring

Problem

I need to get the value of item inside of this string and parse it as JSON. I've got some working code but I feel like it could be optimized (a lot) and cleaned up (a lot). Any tips or pointers are appreciated. Thanks!

My current code:

let result  = script.match(/item:(.*|[\s\S]*)onSelected/gm)[0];
result = result.replace('onSelected', '').replace('item:', '').trim().slice(0, -1);
JSON.parse(result);


Here's the string of javascript I need to pull from:

jQuery(function($) {

    new Selector('itemSelect', {
      item: {"id":9343513159,"title":"The thing","description":"\u003cp\u003eThis is the description\u003c\/p\u003e\n\u003cp\u003eIt has details\u003c\/p\u003e\n","published_at":"2016-12-10T10:08:00-05:00","available":true,"individuals":[{"id":34972221767},{"id":34972221768},{"id":34972221769}],"images":["\/\/cdn.site.com\/s\/files\/1\/0094\/2252\/items\/image.jpg?v=1481382473"],"options":["Time"],"content":""},
      onSelected: selectCallback,
      enableState: true
    });

   // Some stuff here

    $('.main:eq(0)').prepend('Forever');

});

window.mainItem = window.mainItem || {};

mainItem.variables = {
  available : false
};

(function() {
  if (true) {
    mainItem.variables.available = true;
  }
})();

Solution


  • Use .exec to match a group



  • Add comma removed by slice directly into the regexp



  • Use capturing groups: query for [1], not for [0]





let script = document.getElementById('source').text;
var result = /item:(.|[\s\S]),\s*onSelected/gm.exec(script)[1];
console.log(JSON.parse(result));


jQuery(function($) {

new Selector('itemSelect', {
item: {"id":9343513159,"title":"The thing","description":"\u003cp\u003eThis is the description\u003c\/p\u003e\n\u003cp\u003eIt has details\u003c\/p\u003e\n","published_at":"2016-12-10T10:08:00-05:00","available":true,"individuals":[{"id":34972221767},{"id":34972221768},{"id":34972221769}],"images":["\/\/cdn.site.com\/s\/files\/1\/0094\/2252\/items\/image.jpg?v=1481382473"],"options":["Time"],"content":""},
onSelected: selectCallback,
enableState: true
});


// Some stuff here

$('.main:eq(0)').prepend('Forever');

});

window.mainItem = window.mainItem || {};

mainItem.variables = {
available : false
};

(function() {
if (true) {
mainItem.variables.available = true;
}
})()

Context

StackExchange Code Review Q#153313, answer score: 2

Revisions (0)

No revisions yet.