sisl / ngsim_env

Learning human driver models from NGSIM data with imitation learning.
https://arxiv.org/abs/1803.01044
MIT License
172 stars 80 forks source link

How to iterate through a dictionary to get and pass key name to string #19

Open Imfao opened 5 years ago

Imfao commented 5 years ago

I'd like to iterate through a C# dictionary storing nested JSON to retrieve and pass the dictionary key name to a string, in the form of "key1:key1-1:key1-1-1".

After that, a new dictionary is created to use the specially arranged string as its keys.

Finally, desiredDictionary["key1:key1-1:key1-1-1"] = originalDictionary["key1"]["key1-1"]["key1-1-1"].

Please make the answer specific, my apology that I'm new to C# IEnumerable class and JSON.

I've stored the JSON data into a dictionary, the sample JSON is given below.

using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

......
string jsonText = File.ReadAllText(myJsonPath);
var jss = new JavaScriptSerializer();

//this is the dictionary storing JSON
var dictJSON = jss.Deserialize<Dictionary<string, dynamic>>(jsonText); 

//this is the dictionary with keys of specially arranged string 
var desiredDict = new Dictionary<string, string>();
......
......
//Here is a sample JSON
{
    "One": "Hey",

    "Two": {
        "Two": "HeyHey"
           }

     "Three": {
        "Three": {
            "Three": "HeyHeyHey"    
                 }
              } 
}

I need help with the process for dictionary key name retrieval, string completion, and new dictionary value passing. According to the given JSON, desiredDict["Three:Three:Three"] = dictJSON["Three"]["Three"]["Three"] = "HeyHeyHey", The solution is expected to apply on any similar JSON.