I have a scenario, where am reading data from a very large json string, and display the data using the key and value pair, for some reason there are some keys inside the JSON file that share the same key name.
This is my code currently for reading the keys and their values and displaying it on a web page
public IActionResult Entry(string id)
{
var entry = _service.GetALLEntry(id);
JArray json = JArray.Parse(entry.DataContent);
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (JValue item in json)
{
JObject js = JObject.Parse(item.Value.ToString());
foreach (var _it in js)
{
if (_it.Key != "fields")
continue;
foreach (var _ in _it.Value)
{
dict.Add(_.Value<string>("key") "||" _.Value<string>("label"), _.Value<string>("value"));
}
}
}
return View(dict);
}
How can I rename the keys that have similar name in .netcore to another name without editing the keys in the large JSON file?
CodePudding user response:
How can I rename the keys that have similar name in .netcore to another name without editing the keys in the large JSON file?
Append some counter to the key when you save it to the dictionary, the code below it's the idx
value from Linq's .Select
overload:
var entry = _service.GetALLEntry(id);
JArray jarray = JArray.Parse( entry.DataContent );
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach( ( JObject obj, Int32 idx ) in jarray.OfType<JObject>().Select( ( jo, idx ) => ( jo, idx ) ) )
{
if( obj.Property( "fields") is JProperty fp && fp.Value is JObject fieldsObj )
{
String? key = fieldsObj.Property( "key" );
String? value = fieldsObj.Property( "label" );
if( !String.IsNullOrWhiteSpace( key ) )
{
String dictKey = String.Format( CultureInfo.InvariantCulture, "{0}_{1:d}", key, idx );
dict.Add( dictKey, value );
}
}
}