Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7925955
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T18:31:30+00:00 2026-06-03T18:31:30+00:00

An AJAX call is returning a response text that includes a JSON string. I

  • 0

An AJAX call is returning a response text that includes a JSON string. I need to:

  1. extract the JSON string
  2. modify it
  3. then reinsert it to update the original string

I am not too worried about steps 2 and 3, but I can’t figure out how to do step 1. I was thinking about using a regular expression, but I don’t know how as my JSON might have multiple levels with nested objects or arrays.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T18:31:32+00:00Added an answer on June 3, 2026 at 6:31 pm

    You cannot use a regex to extract JSON from an arbitrary text. Since regexes are usually not powerful enough to validate JSON (unless you can use PCRE) they also cannot match it – if they could, they could also validate JSON.

    However, if you know that the top-level element of your JSON is always an object or array, you can go by the following approach:

    • Find the first opening ({ or [) and last closing (} or ]) brace in your string.
    • Try to parse that block of text (including the braces) using JSON.parse(). If it succeeded, finish and return the parsed result.
    • Take the previous closing brace and try parsing that string. If it succeeds, you are done again.
    • Repeat this until you got no brace or one that comes before the current opening brace.
    • Find the first opening brace after the one from step 1. If you did not find any, the string did not contain a JSON object/array and you can stop.
    • Go to step 2.

    Here is a function that extracts a JSON object and returns the object and its position. If you really need top-level arrays, too, it should be to extend:

    function extractJSON(str) {
        var firstOpen, firstClose, candidate;
        firstOpen = str.indexOf('{', firstOpen + 1);
        do {
            firstClose = str.lastIndexOf('}');
            console.log('firstOpen: ' + firstOpen, 'firstClose: ' + firstClose);
            if(firstClose <= firstOpen) {
                return null;
            }
            do {
                candidate = str.substring(firstOpen, firstClose + 1);
                console.log('candidate: ' + candidate);
                try {
                    var res = JSON.parse(candidate);
                    console.log('...found');
                    return [res, firstOpen, firstClose + 1];
                }
                catch(e) {
                    console.log('...failed');
                }
                firstClose = str.substr(0, firstClose).lastIndexOf('}');
            } while(firstClose > firstOpen);
            firstOpen = str.indexOf('{', firstOpen + 1);
        } while(firstOpen != -1);
    }
    
    var obj = {'foo': 'bar', xxx: '} me[ow]'};
    var str = 'blah blah { not {json but here is json: ' + JSON.stringify(obj) + ' and here we have stuff that is } really } not ] json }} at all';
    var result = extractJSON(str);
    console.log('extracted object:', result[0]);
    console.log('expected object :', obj);
    console.log('did it work     ?', JSON.stringify(result[0]) == JSON.stringify(obj) ? 'yes!' : 'no');
    console.log('surrounding str :', str.substr(0, result[1]) + '<JSON>' + str.substr(result[2]));
    

    Demo (executed in the nodejs environment, but should work in a browser, too): https://paste.aeum.net/show/81/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a JSON response returning from an Ajax call but cannot seem to
I have an $.ajax call that includes both a success and error condition: $('input[name=StateName]').live('change',
I have a an ajax call returning JSON to a loop to populate form
I want to make an AJAX call to an HTML-returning page, extract part of
If I have an ajax call off fetching (with a callback) and then some
I am doing an AJAX call that returns some HTML and jQuery: <div id='selected'>Here
i have an ajax call $.ajax({ url: '<%=Url.Action(SaveDetails,Survey) %>', dataType: 'JSON', cache: false, data:
I am doing an Ajax call and on response I would like to hide
I did ajax call and got response in callback function like below: var v=;
I'm having trouble getting a response back from a Jquery ajax call... (It's a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.