Home > Back-end >  How to convert data from two different locations in JSON file to a key(string) and value(double) wit
How to convert data from two different locations in JSON file to a key(string) and value(double) wit

Time:02-28

I am currently trying to download data from the office for national statistics API. The JSON has the format:

"observations": [
    {
        "dimensions": {
            "UnofficialStandardIndustrialClassification": {
                "href": "https://api.beta.ons.gov.uk/v1/code-lists/sic-unofficial/codes/C",
                "id": "C",
                "label": "C : Manufacturing"
            }
        },
        "metadata": {
            "Data Marking": ""
        },
        "observation": "0.4"
    },

The data I am trying to get out is the "label" as the string key and the "observation" as the double value. I am then trying to save this within a dictionary.

The code I am currently using looks like this:

UnityWebRequest www = UnityWebRequest.Get($"{baseUrl}observations?geography=UKG&growthrate=gra&prices=cvm&time={x}&unofficialstandardindustrialclassification=*");
            yield return www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {

                OnsApiResult = www.downloadHandler.text;


                var observations = JObject.Parse(OnsApiResult)["observations"];
                var results = from data in observations
                              select
                                new { label = data["dimensions"]["UnofficialStandardIndustrialClassification"]["label"].ToObject<string>(), observation = data["observation"].ToObject<double>() };


                foreach (var item in results)
                {
                    thisYearData.Add(item.label, item.observation);
                }

the system works when I keep the information as an object, but when I try to convert the data to string and double, I get the error messages:

"FormatException: Input string was not in a correct format."

I am using newtonsoft.JSON, and System.Linq, I am also working on the Unity Game Engine.

Can someone please help me with this? Thank You.

CodePudding user response:

I changed a little your code and it works ok for me

    var observations = JObject.Parse(OnsApiResult)["observations"];
    var results = observations.Select( data => new {
        label = (string)data["dimensions"]["UnofficialStandardIndustrialClassification"]["label"],
        observation = (double)data["observation"]
        });

CodePudding user response:

Your code is working fine in my side ... maybe you have some error in your JSON ....you can try the following imperative approach instead of LINQ to get more info about what happen

foreach(var data in observations)
{
    string label = (string)data["dimensions"]["UnofficialStandardIndustrialClassification"]["label"];
    
    double observation = 0.0;
    if (!double.TryParse((string)data["observation"], out observation))
    {
        // the string observation can not convert to double 
        // log it 
        Console.Error.WriteLine($"ther is problem in json the the value '{data["observation"]}' can not be double");
        continue;
    }
    if (thisYearData.ContainsKey(label))
    {
        // your dictionary alredy has the value 
        Console.Error.WriteLine($"doublicat label : '{label}' alredy exist");
        continue;
    }
    thisYearData.Add(label, observation);    

}
  • Related