-2

I have a string in array format and I want convert to an actual array.

'[[1,"MISSING"],[2,"MISSING"],[6,"MISSING"]]'

Is there any way to convert this to array?

Dimang Chou
  • 595
  • 6
  • 9
  • By using a [JSON parser](https://stackoverflow.com/q/15726197/11683). – GSerg May 03 '19 at 23:23
  • @GSerg That is not valid JSON. – itsme86 May 03 '19 at 23:25
  • @itsme86 Only if you consider the single quotes a part of the the full string. – GSerg May 03 '19 at 23:26
  • 1
    Will you please show the actual string declaration so there's no confusion over what's in the string? Perhaps something like: `string value = "[[1,\"MISSING\"],[2,\"MISSING\"],[6,\"MISSING\"]]";` – Rufus L May 03 '19 at 23:41
  • This is the actual string that I retrieved from a field of legacy database table which had been developed for many generations, there is no document tell why they saved in this way? – Dimang Chou May 04 '19 at 16:01

1 Answers1

2

ok first thing... C# strings use double quote but ok ignoring that I am assuming that this is coming from JavaScript and you want to process it in c# is that correct ?

var source= "[[1,\"MISSING\"],[2,\"MISSING\"],[6,\"MISSING\"]]";
// doing it by hand. you could clearly do this more consisely but verbose like this makes it easy to follow i think 
var arrayWithNoExternalCode = new string[10];
var arrayItems = source.Replace("[[","").Replace("]]","").Split(new[] { "],["},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayItems)
{
var parts = item.Split(new[] { ",\""},StringSplitOptions.RemoveEmptyEntries);
var index = parts[0];
var indexValue = parts[1].Replace("\"", "");
Console.WriteLine($"array index: {index}='{indexValue}'");
arrayWithNoExternalCode[Convert.ToInt32(index)] = indexValue;
}
// add using ServiceStack.Text
// via nuget: Install-Package ServiceStack.Text -Version 5.5.0
var easyArray = source.FromJson<string[][]>();
  • @RufusL given skill implied by the nature of the question I tried to give a reply that would be very easy to understand/follow. – Matt Van Horn May 03 '19 at 23:50