Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it.

The response I receive is in the form of a formatted string:

{
    "questionId": 18196101,
    "externalQuestionId": "bcc38f7d30ea44ad908d8166dafa5556",
    "category": "Employment Law",
    "secondaryCategory": "",
    "partnerName": "",
    "questionTitle": "I sold my business but was offered a job with the company as",
    "questionText": "I sold my business but was offered a job with the company as manager..."
}

The string representation is:

'{"questionId":18196101,"externalQuestionId":"bcc38f7d30ea44ad908d8166dafa5556","category":"Employment Law","secondaryCategory":"","partnerName":"","questionTitle":"I sold my business but was offered a job with the company as","questionText":"I sold my business but was offered a job with the company as manager..."}'

Given that I have access to both the questionTitle and questionText, I can search for their indexes within the string. This becomes necessary since this object may be embedded in a larger response at different positions.

The extraction task involves retrieving the externalQuestionId, such as

"bcc38f7d30ea44ad908d8166dafa5556"
in this example.

Due to the dynamic nature of the numbers involved, identifying the indexes of known parameters is crucial.

Essentially, with knowledge of the starting index of questionTitle, the challenge is to locate the nearest occurrence of externalQuestionId.

Answer №1

Special thanks to @nnnnnn for recommending the utilization of the .lastIndexOf() method.

For my specific situation, I devised a straightforward function that takes the complete text and a specific fragment as parameters, then extracts the necessary data.

function obtainQuestionId(fullText, textFragment) {
var newString = fullText.substr(fullText.lastIndexOf("externalQuestionId", fullText.indexOf(textFragment)));
return newString.substr(21, newString.indexOf(",") - 22);
}

var str = '{"questionId":18196101,"externalQuestionId":"bcc38f7d30ea44ad908d8166dafa5556","category":"Employment Law","secondaryCategory":"","partnerName":"","questionTitle":"I sold my business but was offered a job with the company as","questionText":"I sold my business but was offered a job with the company as manager..."}'
var frag = 'I sold my business but was offered a job with the company as","questionText":"I sold my business b';

console.log(obtainQuestionId(str, frag));

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

Creating a JSON object in JavaScript using an array

Can anyone assist me with the following code snippet for formatting the current month? var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set&apos ...

Invoke a function or variable based on a string parameter within a JavaScript/React function dynamically

I am currently exploring ways to dynamically call a function based on a string or reference a variable using a string. For example: import React, {useState} from 'react' const array = [ { text: 'count1', setFunctionName: &apo ...

Sending a string within a JSON payload using Python

I'm looking to incorporate a randomly generated password into my payload. Here's what I've got so far: import requests import json import random import string #generate 12 character password alphabet = string.ascii_letters + string.digits + ...

Unable to upload photo using Ajax request

I am in the process of trying to utilize Ajax to upload an image, so that it can be posted after the submit button is clicked. Here is the flow: User uploads image -> Ajax call is made to upload photo User clicks submit -> Post is shown to the user along ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

Is there a way to prevent the slide-out bar from automatically hiding when selecting an item from its list?

I am facing an issue with my dashboard that has a slideout sidebar. Whenever I press the toggle button, the sidebar slides out as expected. However, when I click on any tab within the sidebar, it hides again. I only want it to hide when toggled. My code is ...

Tips for ensuring all my onclick event are clickable in iOS browser

Currently, I am developing a web page using HTML5 and JQuery Mobile. I have encountered an issue where the onclick function does not work on iOS device browsers. Is there a way to change all onclick events to be accessible through tapping instead? This wou ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Combine several elements in a single jQuery scrollreveal function

I am currently working on a webpage that utilizes the jQuery library plugin scrollreveal to gradually reveal different html elements when the page loads. The functionality of the code is working correctly at the moment, but I have noticed that there is a d ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Retrieving information from an object using JavaScript

Hello, I am facing a challenge with extracting data from an object via a web API in ReactJS. It seems like the data returned by the API is not structured properly as a JavaScript object. To view the issue directly in your browser visit: I need assistance ...

"Using Node.js Express 4.4 to efficiently upload files and store them in a dynamically

Looking for recommendations on the most efficient method to upload a file in node.js using express 4.4.1 and save it to a dynamically created directory? For example, like this: /uploads/john/image.png, uploads/mike/2.png ...

What steps do I need to take in order to create functions that are

I have 10 functions with similar structures: function socialMedia_ajax(media){ return ajaxRequest('search/' + media + 'id', media + 'id').then( function(res) { var imgStatus = res[1].length > 0 ? "c ...

Attempting to gather data from an HTML form and perform calculations on it using JavaScript

Looking for help with extracting user input from HTML and performing mathematical operations in JavaScript. Coming from a Python background, the variable system in JavaScript is confusing to me. Can someone provide guidance on how to achieve this? <div ...

Performing JSON data extraction and conversion using JavaScript

Hello! I'm working with a script that converts data into an array, but I want to enhance it so that I can extract and convert data for each object (arb, astar, aurora, avax, baba, bsc, etc.), as shown in the screenshot. Here is the current script tha ...

Is it possible for an angular directive to transmit arguments to functions within specified expressions in the directive's attributes?

I am working on a form directive that utilizes a specific callback attribute with an isolate scope: scope: { callback: '&' } This directive is placed within an ng-repeat, where the expression passed in includes the id of the object as an ar ...

Format JSON data with each object appearing on a new row

Has anyone found a solution for importing test data to mongodb using mongo atlas when each document needs to be on a separate line? I'm wondering if there are any online tools available to assist with formatting or if I should create my own script. ...

A groundbreaking algorithm engineered to launch a sequence of distinct hyperlinks upon each button press

I have a unique script that allows me to open links randomly, but now I want to create a new script that opens links sequentially and goes back to the initial one. For example, clicking a button will open link1, then clicking it again will open link2, an ...

What is the reason why calling setState does not update the local state?

Hello everyone, I came across an intriguing React task and I'm struggling a bit with finding the solution. Task: Can you figure out why this code isn't working and fix it? Code: class BugFixer extends React.Component { constructor(props) { ...