Using Javascript regex for extracting JSON string content including property values within HTML code

I have data in the following format that is not valid JSON. I am trying to convert it using regex, but the parse won't go through. For more details, refer to this question which I've tried.

The problem lies in the fact that the response string also contains HTML, variables, and trailing commas. Below is the test data that is failing:

`var _nr_metadata = {
    site_base_url : "http://newsrack.in",
    issue_name    : "iihs_feeds",
    category_name : "Chikungunya",
    listing_url   : "/stories/servelots/iihs_feeds/16"
  }
  var _nr_stories = [
    {
      title  : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
      url    : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
      source : "The Tribune",
      date   : "25.10.2017",
      desc   : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department ..."
    },
    ...
]

The expected output should be a valid JSON for use in the rest of my application. Unfortunately, I do not have control over modifying the server response.

Answer №1

This server doesn't actually function as a JSON API; rather, it produces JavaScript code. Even the slightest alteration to the response format, like using semi-colons to terminate statements, could disrupt an attempt to parse it successfully. Without knowledge of your specific use case, this approach seems risky.

Despite these challenges, attempting to parse it using JSON.parse appears to be less hazardous than other methods. I managed to get it to parse by implementing these replacements:

var text = document.getElementById('response').innerText;

// 1. Convert vars to properties
text = text.replace(/^\s*var\s+(\w+)\s*=/gm, ',"$1":');

// 2. Quote the keys
text = text.replace(/^\s*(\w+)\s*:/gm, '"$1":');

// 3. Get rid of the '' at the end
text = text.replace(/^\s*\},[\n\s]*''.*$/gm, '}');

// 4. Remove the comma that step 1 added at the start
text = text.replace(/^\s*,/g, '');

// 5. Wrap everything in an object
text = '{' + text + '}';

var obj = JSON.parse(text);

console.log(obj);
<script id="response" type="custom">
var _nr_metadata = {
    site_base_url : "http://newsrack.in",
    ...
    // Truncated for brevity
    ...
}
</script>

I have employed the m flag in multiple RegEx patterns assuming certain data starts at the beginning of a line, which might be too fragile depending on variations in your source data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to customize the spacing of grid lines in chartist.js?

I am struggling with chartist.js. I want to increase the spacing between y-axis gridlines by 40px. (Currently set at 36px) I have tried looking for examples, but haven't found any. .ct-grids line { stroke: #fff; opacity: .05; stroke-dasharray: ...

Transferring a JSON document to an Express server with JavaScript

I've recently started learning JavaScript and I'm facing an issue with sending a JSON file to my server (Express) so that I can parse its contents and use them in the web application I'm developing. Here's my current setup: a JSON fil ...

What causes the delay in CSS animations?

Is there a way to trigger an "updating" image to spin while a long JavaScript function is running? I am currently using JQuery to add a class called "spinning", defined in my CSS for the animation. The problem is that when I add the class and then call a l ...

What is the ideal framerate for smooth animation?

I'm looking to add a snow animation using JavaScript. I currently have it running at 200ms which is decent but not smooth enough. Would changing the interval to 20ms make it more fluid, or would it be inefficient and strain the CPU? window.setInterva ...

Error: You cannot implement an import statement beyond a module while utilizing reactjs CDN Links

I am developing a Reactjs app using react CDN Links instead of 'npx create-react-app'. I have set up an index.html, index.js, and App.js files. My goal is to import the App.js component into the Index.js file using import App from '../compon ...

How can I navigate through all the divs by setting an interval slider with a random starting point?

I have a Jsonp request that returns a block of HTML with the following structure: <div id="slider_wrapper" style=""> <div style="xxx" ><section style="xx">xx</section></div> <div style="xxx" ><section style=" ...

Navigating a Two-Dimensional Array in JavaScript

Below is an example of an array that I am working with: let myArray = [["ABC", "123"], ["DEF", "456"]]; If I need to retrieve the value "123" when searching for "ABC," what is the correct way to ...

What is the best way to create a regular expression that can detect a string containing a full stop ('.') in the middle and ending with a comma?

string input= "devname=B399601569,devid=B39601569,logid=000013,type=traffic,srcip=192.168.192.123,srcport=2072,dstip=10.180.1.105,dstport=3206" I attempted the following expression: Pattern p = Pattern.compile("(srcip=)(\\d+)((.*)?)(dstip=)(&bs ...

Unable to alter the height of the element

I am attempting to resize an element by dragging, similar to this example. I have created a simple directive for this purpose: @Directive({ selector: '[drag-resize]' }) export class DragResizeDirective { private dragging: boolean; const ...

Node js can sometimes be unreliable

After installing the always module for nodejs, I noticed that when I run my server using "always server.js", it runs and restarts as expected. However, after about 10 restarts, the server stops restarting altogether. The always process continues to run, ...

Premature audio cutoffs in Javascript/CSS when using onmousedown event

One issue I'm facing is that a small beep sound should play when clicking on a link, but it gets cut off unless the click is held down. <script> var beep = new Audio(); beep.src = "audio/select.mp3"; </script> <div cla ...

An Iframe lacks the ability to showcase HTML content, unlike a browser which is capable of doing

I'm struggling to get my Iframe to show the html string properly. Here's the content of the string: var='<BODY style="MARGIN: 0px" bgColor=#ffffff marginwidth="0" marginheight="0"> <SCRIPT language=JavaScript> var Caller_User_Ty ...

Create a feature that allows users to view photos similar to the way it

I want to incorporate a Twitter feed on my website that displays images posted. Instead of having the images redirecting users to Twitter when clicked, I would like them to reveal themselves underneath when a link labeled "View Photo" is clicked, and then ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

Concentrate on elements that are activated without the need for clicking

Is it possible to trigger an action when an input is focused without the focus event being initiated by a click? $('#input').focus(function(){ if(not triggered by click) { alert('Hello!'); } }); ...

Is there a way to construct a table within MySql?

I am currently working with a JSON file and attempting to generate a table that displays the information it contains. { "name": "John Smith", "sku": "20223", "shipTo": { "name" ...

Using mappers to create a computed property for two-way binding

In my Vue 2 project, I make use of vuex. Currently, I am working on implementing two-way binding for this HTML element: <input v-model="message"> computed: { message: { get () { return this.$store.state.obj.message }, ...

Struggling with integrating HTML Canvas within Vue.js

Currently, I am attempting to upload an image by utilizing HTML canvas. My decision to use canvas stems from the fact that I will be superimposing additional images based on the data received from the API, and this process seems more straightforward when u ...

I'm new to React and curious - why do we need to use ReactDOM.render() to update HTML instead of just writing the HTML directly?

I am new to learning react and am struggling to grasp why we need to utilize reactDOM.render() instead of just writing plain HTML code. ...

Instructions for successfully populating Excel without encountering error warnings by utilizing JSONArray and POI

When generating an Excel file using the `POI` library, I am iterating through a JSON array to populate values in cells. Here is how my JSON array structure looks: [[1,"A","0","6","0","6"],[2,"B","3","3","0","6"],[3,"C","3","0","0","3"],[4,"D","4","0","0", ...