Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Extract json object from mixed data text/js file

I need to parse reactjs file in main.451e57c9.js to retrieve version number with C#.
This file contains mixed data, here is little part of it:

.....inally{if(s)throw i}}return a}}(e,t)||xe(e,t)||we()}var Se=
JSON.parse('{"shortVersion":"v3.1.56"}')
,Ne="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA
AASAAAAAqCAYAAAATb4ZSAAAACXBIWXMAAAsTAAALEw.....

I need to extract json data of {"shortVersion":"v3.1.56"}

The last time I tried to simply find the string shortVersion and return a certain number of characters after, but it seems like I’m trying to create the bicycle from scratch. Is there proper way to identify and extract json from the mixed text?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static void findVersion()
{
    var partialName = "main.*.js";
    string[] filesInDir = Directory.GetFiles(@pathToFile, partialName);

    var lines = File.ReadLines(filesInDir[0]);

    foreach (var line in File.ReadLines(filesInDir[0]))
    {
        string keyword = "shortVersion";
        int indx = line.IndexOf(keyword);

        if (indx != -1)
        {
            string code = line.Substring(indx + keyword.Length);
            Console.WriteLine(code);
        }
    }
}

RESULT

":"v3.1.56"}'),Ne="data:image/png;base64,iVBORw0KGgoAA.....

>Solution :

Try below method –

 public static object ExtractJsonFromText(string mixedStrng)
    {
        for (var i = mixedStrng.IndexOf('{'); i > -1; i = mixedStrng.IndexOf('{', i + 1))
        {
            for (var j = mixedStrng.LastIndexOf('}'); j > -1; j = mixedStrng.LastIndexOf("}", j -1))
            {
                var jsonProbe = mixedStrng.Substring(i, j - i + 1);
                try
                {
                    return JsonConvert.DeserializeObject(jsonProbe);
                }
                catch
                {                        
                }
            }
        }
        return null;
    }

Fiddle
https://dotnetfiddle.net/N1jiWH

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading