1

I have this string : [{"Weight":70,"CustomerId":45},{"Weight":30,"CustomerId":733‌​}] please note that quotation marks are parts of this string I need to extract the digits for 'weight' and 'customerId' separately. I tried to do it like this for weight :

MatchCollection Weightmatches = Regex.Matches(r["Formula"].ToString(), @"""Weight"":(\d+),");

(there might be more Weight or Customer numbers on this string)

but I can't seem to understand how to isolate the numbers alone.

please help!!

4
  • 4
    You should not use a regex to parse JSON, in C#, use JSON.NET to do that. Commented Apr 25, 2017 at 7:50
  • Note that it is not yet clear what output you need. Commented Apr 25, 2017 at 9:04
  • Sorry, I still do not understand: do you want to get a list of KeyValuePairs with Wieght as keys and CustomerId as values? var results = new List<KeyValuePair<int, int>>();? Commented Apr 25, 2017 at 9:16
  • yes, I thought about tuple<int,int> at first . but this is a better option Commented Apr 25, 2017 at 9:18

2 Answers 2

1

To properly parse JSON, it is recommended to use a JSON parser. JSON.NET provides one, just install it as a NuGet package and use the following code:

var json_data = "[{\"Weight\":70,\"CustomerId\":45},{\"Weight\":30,\"CustomerId\":733}]";
dynamic parsedObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json_data);
var results = new List<KeyValuePair<int, int>>();
foreach (dynamic entry in parsedObject)
{
    if (entry.Weight != null && entry.CustomerId != null)
        results.Add(new KeyValuePair<int, int>(int.Parse(entry.Weight.ToString()), int.Parse(entry.CustomerId.ToString())));
}

The output:

enter image description here

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

Comments

0

Using a JSON parser is the right answer here. But I suppose you could do a Regex search similar to this:

(?:["][^"]+["] : (\d+))

Or if you want to capture the text as well:

(?:["]([^"]+)["] : (\d+))

5 Comments

can you please write the full line? something is not clear to me with the syntax
@Jonathan: Do not use regex, please. Do you want me to post a JSON.NET based solution? It is not really that difficult, and is much more readable.
@Jonathan: Then please share the full JSON data in the question as your current string is not a valid JSON.
[{"Weight":70,"CustomerId":45},{"Weight":30,"CustomerId":733}]
Please add it to the question and specify what output you need.

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.