Home > Net >  How to split string having multiple JSON data string
How to split string having multiple JSON data string

Time:10-14

I'm trying to split a string having two valid JSON strings in a file. My data looks something like this

{
    "abc": {
        "Version": "1.0",
        "Allocations": [
            {
                "xyz": "40014645",
                "efg": -5.0
            }
        ],
        "Date": "2022-10-11T07:29:00.000Z"
    },
    "tyu": 255,
    "pou": 2139,
}
{
    "abc": {
        "Version": "1.0",
        "Allocations": [
            {
                "xyz": "40014644",
                "efg": -3.0,
            }
        ],
        "Date": "2022-10-11T08:50:00.000Z"
    },
    "tyu": 255,
    "pou": 2139,
}

My requirement is to separate the two JSON and get individual JSON string in a variable like

{
    "abc": {
        "Version": "1.0",
        "Allocations": [
            {
                "xyz": "40014645",
                "efg": -5.0
            }
        ],
        "Date": "2022-10-11T07:29:00.000Z"
    },
    "tyu": 255,
    "pou": 2139,
}

and

{
    "abc": {
        "Version": "1.0",
        "Allocations": [
            {
                "xyz": "40014644",
                "efg": -3.0,
            }
        ],
        "Date": "2022-10-11T08:50:00.000Z"
    },
    "tyu": 255,
    "pou": 2139,
}

Can anyone help me with this? The schema doesn't have any class as such. It's just a string format file with some values.

CodePudding user response:

This might be a little wacky, but I'm taking your string as is and assuming you cannot change it. I'm going to convert it into a json array, to do this we need to wrap in brackets, but also add commas after each outer closing curly braces. This code snippet does it for me.

Stack<char> myStack = new Stack<char>();
string s = "";

//Find each outside curly brace and add a comma on the closing brace
foreach(char c in jsonString){
    if(c == '{'){
        myStack.Push(c);
    }
    if(c == '}'){
        myStack.Pop();
        if(myStack.Count == 0){
            //Closing curly, add a comma after
            s  = c; 
            s  = ',';
            continue;
        }
    }
    s  = c;
}

//Wrap in brackets to turn into array
s = s.Insert(0, "[");
s  = "]";

var options = new JsonSerializerOptions()
{
    AllowTrailingCommas = true
};

var obj = JsonSerializer.Deserialize<object[]>(s, options);
Console.WriteLine(obj[0].ToString());
Console.WriteLine(obj[1].ToString());

CodePudding user response:

You can achieve your objective using both string.Replace and string.Split.

string text = File.ReadAllText("json.txt");

// inject curly brackets so that we can split without loosing
// one on each side
text = text.Replace("}\r\n{", "}}\r\n{{");

var jsonArr = text.Split("}\r\n{");

// access first json
Console.WriteLine(jsonArr[0]);

Output of first json:

{
    "abc": {
        "Version": "1.0",
        "Allocations": [
            {
                "xyz": "40014645",
                "efg": -5.0
            }
        ],
        "Date": "2022-10-11T07:29:00.000Z"
    },
    "tyu": 255,
    "pou": 2139,
}

Output

CodePudding user response:

If you have only 2 jsons in one file, I would try somethig like this

    var i = 0;
    var countStart = false;
    for (i = 0; i < text.Length; i  )
    {
        if (text[i] == '}') countStart = true;
        else if (countStart)
        {
            if (text[i] == ',' || text[i] == ']') countStart = false;
            else if (text[i] == '{')  break; 
        }
    }

     var json1 = text.Substring(0, i - 1);
     var json2 = text.Substring(i);

or it is better to convert it to a json array

    text = "["   text.Substring(0, i - 1)   ",\n"   text.Substring(i)   "]";
    var jsonArray=JArray.Parse(text);
    string version1 = jsonArray[0]["abc"]["Version"].ToString(); // "1.0"

if you have more than 2 jsons, this algorithm could be adjusted very easily too.

  • Related