1

Example of JavaScript arrays:

var array_1 = [["string 1", 2013, "string 2"], "string 3", ["string 4", , "string 5"]];
/* array_1[0][2] = "string 2" */

var array_2 = [1, , ["string 1", "string 2"]];
/* array_2[0][0] = 1 */

I need to parse JS arrays like it to c# jagged array or any other object that can access each child string by index easy, by function, with:

  • number become string (1 => "1")
  • null become "" (string with length = 0).

Can you help me how to do this? Thank you very much!

0

5 Answers 5

4
+50

using Json.NET

// using
using Newtonsoft.Json.Linq;


string JSarray_1 = @"[[""string 1"", 2013, ""string 2""], ""string 3"", [""string 4"", , ""string 5""]]";
JObject j = JObject.Parse("{\"j\":" + JSarray_1 + "}");
MessageBox.Show((string)j["j"][0][2]); // "string 2"
Sign up to request clarification or add additional context in comments.

Comments

2

See the C# language documentation: "Multidimensional Arrays (C#)"

string[,] items = new  string[,] {{"string 1","string 2"},...};

1 Comment

Technically, what the OP seems to have there is a jagged array, not a multi-dimensional one.
1

I think what TuyenTk is looking for, and emigue is trying to describe is to use a library which does the "magic"(=parsing)

I'd recommend JSON.Net since it's the one I use all the time - but I guess there are plenty of these out there.

The linked page also includes some simple examples on how to use it.

About replacing null with emptystring:

var myValue = origValue ?? String.Empty;

if origValue is null myValue will be set to "", otherwise the expression will evaluate to origValue;

For further information on "??", or the "null-coalescing operator" as it's called, see the doc

Comments

0

As Jagged Arrays

string[][] items = new string[3][];

items [0] = new string[2];
items [1] = new string[1];
items [2] = new string[2];

items[0][0] = "string1";
items[0][1] = "string3";
items[1][0] = "string4";
items[2][0] = "string5";
items[2][1] = "string6";

OR

string[][] items = new string[][] 
{
    new string[] {"string1", "string3"},
    new string[] {"string4"},
    new string[] {"string5", "string6"}
};

Comments

0

If you need parse javascript arrays to c# arrays, You can serialize Javascript arrays to JSON and then deserialize JSON to C# array.

Previously, you need to do one transformation: replace "" by null in Javascript array representation as string.

Then, you can make something like this:

var JSArrayString = @"{"array_1": [["string 1", 2013, "string 2"], "string 3", ["string 4", null, "string 5"]]}";
var CSharpDict = SomeJSONLibrary.Deserialize(JSString);
var CSharpArray = CSharpDict["array_1"];
var myItem = CSharpArray[0][2];

1 Comment

Sorry, can you explain more clearly? From JSArrayString to CSharpArray[0][2] is a long distance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.