0

I have a string with a formatting like this:

[["addr","field"],["[email protected]",1000],["[email protected]",1001],["[email protected]",1002],["67656x3434",100],["99999",511],["79898",400],["545654",561],["7979",200],["6776767",201],["4656",300],["88888",5000]]

I want to get the addre (value) base on the field (key). I read some article about how to get value from a JSON string at:

Read JSON string as key value

How to read this json string using c#?

But it does not work for me.

Any ideas, guys?

5
  • And for some language? Commented Sep 12, 2014 at 2:48
  • Sorry, that's my bad. I use C# language, Deep Commented Sep 12, 2014 at 4:39
  • Well, and i wanted write js solution ))) And c# not have lib for json parse? Commented Sep 12, 2014 at 4:52
  • C# has JsonObject class for json parse. But the problem is my string is not a JSON, just likes as its format. Commented Sep 12, 2014 at 8:17
  • Your example is pure JSON. Parse it with library. And after make your inner format Commented Sep 12, 2014 at 17:01

1 Answer 1

1

If you use the Json.Net library to parse the JSON, you can get the data into a Dictionary<int, string> like this:

JToken token = JToken.Parse(json);

Dictionary<int, string> dict = 
    token.Skip(1).ToDictionary(a => (int)a[1], a => (string)a[0]);

Then you can use the dictionary like you normally would to access the data.

Demo: https://dotnetfiddle.net/Icyv1O


If you can only use .Net 2.0, you can do the same thing like this:

JToken token = JToken.Parse(json);
Dictionary<int, string> dict = new Dictionary<int, string>();

bool skippedFirstItem = false;
foreach (JToken item in token)
{
    if (skippedFirstItem)
        dict.Add((int)item[1], (string)item[0]);
    else
        skippedFirstItem = true;
}

Demo: https://dotnetfiddle.net/zDvQFF

Sign up to request clarification or add additional context in comments.

2 Comments

This is an answer that I need. How about your solution in case of using .NET 2.0 which does not support Lamda Expression?
OK, I've updated my answer to show how to do this in .NET 2.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.