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

Ways to allow scroll events on top of an overlay without passing click events

My goal is to develop a unique map annotation tool with custom controls, not relying on the built-in features of map providers. Imagine something like this: https://i.sstatic.net/70Yj7.gif I had the idea of placing a canvas over the map for this purpose ...

What are the potential drawbacks of utilizing setState within the componentDidUpdate method in React?

I am facing a situation where I need to update a child component's state whenever a prop changes. Here is how I have approached it: componentDidUpdate(prevProps) { const { searchValue, searchCriterion } = this.props; if (searchValue !== prevP ...

A step-by-step guide on extracting all documents within a directory collection from the official national archives website using the R programming language

I'm currently seeking a way to scrape all available files for a data file series on archive.gov programmatically using R. It seems that archives.gov utilizes JavaScript. My objective is to extract the URL of each available file along with its name. T ...

Handling dynamic properties in C# when working with Json to C# object conversion

I've been working on implementing JSON structure in C# objects, and I'm trying to figure out how to select the correct object based on the type specified. Here is an example: public class RootObject { public string name { get; set; } pub ...

Angular @Input set function not being activated during unit testing

Within my Component @Input('price') set setPrice(price) { this.price = price; this.modifyTotalAmount(); } Unit Testing (component.spec.ts) it('should execute function ', () => { spyOn(fixture.componentInstance, ' ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Scrolling to a specific position on a page when a Vue 3 component appears is a must-do for

When I click a button, my basic form component appears without using the router. I would like the scroll position of the form to automatically move down slightly (for example, on the y-axis at 40) once it is displayed. However, I am unsure of how to achi ...

Tips for minimizing the padding/space between dynamically generated div elements using html and css

Currently, I have 4 dropdown menus where I can choose various options related to health procedures: Area, specialty, group, and subgroup. Whenever I select a subgroup, it dynamically displays the procedures on the page. However, the issue I am facing is th ...

How to Transfer an Embedded Document to an Array within the Same Parent Document in MongoDB

I am working with a Mongo collection that has objects structured like this: { id: , ... events: [{},{},{} ...] ... runtime: { field1: Date, field2: Date, field3: boolean } } When a specific route is queried, I need to extract fiel ...

Tips for utilizing the Apollo cache consistently during page transitions in NextJs

In the official examples repository of NextJS, I found this apolloClient.js file: import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client' import { concatPagination } from '@apollo/client/utilities' import merge from &apos ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Utilizing dynamic JSON lists in Spring MVC

Currently, I have a new form for Person that includes a table of objects structured like so: <table class="table table-striped table-condensed flip-content"> <thead class="flip-content"> <tr> <th width="20%"> ...

Scrolling without limits - cylindrical webpage (CSS/JS)

Is it possible to create a page that infinitely scrolls from top to top without going straight back to the top, but instead showing the bottom content below after reaching it? Imagine being able to scroll up and see the bottom above the top like a 3D cylin ...

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

What is the best choice for code design patterns in a nodejs environment? What are the key considerations for creating a well-

Although I have a background in games development using C/C++/C#, I have recently delved into automated testing and now I am eager to learn more about backend development. My current project involves creating a platform for automated backups, building fr ...

How can Jquery detect when users click on 'ok' in confirm() pop-up dialogs?

Within my application, I have multiple confirmation dialogues that appear when users attempt to delete certain items. Is there a method to determine if a user has clicked the 'ok' button on any of these dialogues globally so that I can execute a ...

decipher intricate JSON data

After converting a JSON object from a YAML file, I attempted to serialize it but encountered errors. {'info': {'city': 'Southampton', 'dates': [datetime.date(2005, 6, 13)], 'gender': 'male', ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Dropzone.js: Creating a personalized file explorer to include files that have already been uploaded

Don't worry, this isn't your typical "can't load files from the server" query... I'm looking to allow users to view files on the server in a bootstrap modal and then select specific files. After selection, I want to close the modal and ...