In my project client send me this JSON string.
{
"onlineRequest": {
"CustomerCode": "AB432A",
"MobileNumber": "75484568",
"ProductNo": "100",
"JsonFile": {
"evaluation": {
"number": [
{
"#para-id": "5656",
"#new-code": "",
"#text": "Hello America"
},
{
"#para-id": "3302",
"#new-code": "100",
"#text": "Hello Japan"
}
]
}
}
}
}
This JSON contains inner JSON called JsonFile. Now I need to set the values to this JSON file as follows.
if #para-id = 5656, then #new-code = "0000"
if #para-id = 3302, then #new-code = "1111"
Expected Output:
{
"onlineRequest": {
"CustomerCode": "AB432A",
"MobileNumber": "75484568",
"ProductNo": "100",
"JsonFile": {
"evaluation": {
"number": [
{
"#para-id": "5656",
"#new-code": "0000",
"#text": "Hello America"
},
{
"#para-id": "3302",
"#new-code": "1111",
"#text": "Hello Japan"
}
]
}
}
}
}
How can I do this?
Can be easily done with Newtonsoft.Json:
var source = #"{
""onlineRequest"": {
""CustomerCode"": ""AB432A"",
""MobileNumber"": ""75484568"",
""ProductNo"": ""100"",
""JsonFile"": {
""evaluation"": {
""number"": [
{
""#para-id"": ""5656"",
""#new-code"": """",
""#text"": ""Hello America""
},
{
""#para-id"": ""3302"",
""#new-code"": ""100"",
""#text"": ""Hello Japan""
}
]
}
}
}
}";
var json = JToken.Parse(source);
var dict = new Dictionary<string, string>
{
["5656"] = "0000",
["3302"] = "1000",
};
foreach (var number in json.SelectToken("onlineRequest.JsonFile.evaluation.number").ToArray())
{
var id = (string)number["#para-id"];
if (id != null && dict.TryGetValue(id, out var code))
{
number["#new-code"] = code;
}
}
Related
For example we have following document in elastic:
{
"name": "Bob",
"age": "22",
"phrase": "ohohoho",
"date": "2022-10-20T00:00:00Z"
}
string phrase ;
DateTime? date;
Then we want put following:
{
"name": "not Bob",
"age": "22",
"phrase": null,
"date": null
}
in c#:
var updateRequest = new UpdateRequest<T, T>(entity)
{
ScriptedUpsert = true,
Script = new InlineScript(
$"if (someCondition) {{ctx._source.putAll(params.entity);}} else {{ctx.op = \"noop\";}}")
{
Lang = "painless",
Params = new Dictionary<string, object>() { { "entity", entity } },
},
Upsert = Activator.CreateInstance<T>()
};
but in the end it will not update phrase and date.
It makes following request:
POST /myIndex/_update/b90278fd-1a66-40bf-b775-d076122c6c02
{
"script": {
"source": ""if (someCondition) {{ctx._source.putAll(params.entity);}} else {{ctx.op = \"noop\";}}"",
"lang": "painless",
"params": {
"entity": {
"name": "",
"age": 22
}
}
},
"upsert": {
"age": 0
}
}
Idk why but it skips all fields with null.
How to update nullable fields to null?
NEST does not support sending null values by default.
You can have a check in script such that if a value is not passed then you can remove it from document.
var updateRequest = new UpdateRequest<T, T(entity)
{
ScriptedUpsert = true,
Script = new InlineScript($"if (params.entity.phrase==null)ctx._source.remove('phrase');")
{
Lang = "painless",
Params = new Dictionary<string, object>() { { "entity", entity } },
},
Upsert = Activator.CreateInstance<T>()
};
You can check for more details here
I have a JSON structure that contains different levels. How to iterate the JSON and get all values of a particular key in JSON in C#
Below is my JSON file
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"type": "root",
"childern": [
{
"cid": "67",
"cname": "cname1",
"childern": [
{
"reading": [
{
"id": 121,
"name": "test1"
},
{
"id": 1121,
"name": "test11"
}
]
}
]
},
{
"cid": "454",
"cname": "cname14",
"childern": [
{
"reading": [
{
"id": 454,
"name": "test14"
},
{
"id": 21,
"name": "test141"
}
]
}
]
}
]
}
This is the JSON format. I am trying to get the value in the below format.
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"value": [
{
"id": 121,
"name": "test1",
"cid": "67",
"cname": "cname1"
},
{
"id": 1121,
"name": "test11",
"cid": "67",
"cname": "cname1"
},
{
"id": 124234,
"cname": "test12342",
"cid": "67",
"name": "cname1"
},
{
"id": 454,
"name": "test14",
"cid": "454",
"cname": "cname14"
},
{
"id": 21,
"name": "test141",
"cid": "454",
"cname": "cname14"
},
{
"id": 121,
"name": "test123122",
"cid": "454",
"cname": "cname14"
}
]
}
fetching all the reading key and its value-added to array with its cid and came. is it possible?
advanced thanks for the help
my code in c# is
public string SensorList(string entireData)
{
if (string.IsNullOrEmpty(entireData))
{
return string.Empty;
}
var returnObj = new Jobject ();
JObject o = JObject.Parse(entireData);
var childern = o["children"];
returnObj.Add("name" = o ["name"];
returnObj.Add("id" = o ["id"];
returnObj.Add("value" = o ["value"];
var valuearry = new JArray();
foreach(var data in childern)
{
foreach(var reading in data["reading"])
{
var valobj = new Jobject ();
valobj.Add( "cid",data["id"])
valobj.Add( "cname",data["name"])
valobj.Add( "name",reading["id"])
valobj.Add( "id",reading["name"])
valuearry.add()
if(data.containsKey("children"))
{
var sensorInfo = SensorList(data["children"]);
}
}
returnObj.Add("value",valuearry);
// var output = sensorInfo.SelectMany(x => ((JObject)x).Properties().Select(y => new JObject {
// new JProperty("id",y.Name),
// new JProperty("name",y.Value["name"])
// })).ToList();
// var returnArray = new JArray(output);
return returnObj.ToString();
}
}
recurring part is not working and take too much time for other long JSON file
I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:
This is my Data Structure and I'm trying to access it with simpleJason, through unity/c#, I have accidentally gotten the right data here and there, and otherwise gotten completely empty arrays, I'd like to know if my JSON file is improperly setup for my data structure, or if the parser is somehow falling though, or not properly matching what I'm looking for.
JSON File:
{
"categories": [
{
"name" : "entertainment",
"projects": [
{
"name": "Awards",
"description": "Awards Shows",
"credits": [
"Lead Engineer - Dave Jones",
"VFX Supervisor - John Adrian",
"CG Supervisor - Evan Klein"
],
"meta": [
"awards",
"show",
"stars",
"red carpet"
],
"assets": [
{
"name": "Screen Actors Guild Awards",
"filename": "SAG_Awards.mp4",
"icon": "sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "No Awards",
"filename": "No_SAG_Awards.mp4",
"icon": "no_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "None Awds",
"filename": "None_SAG_Awards.mp4",
"icon": "none_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
}
]
}
]
}
]
}
This is the struct :
private struct jsonAsset {
public string category;
public string project;
public string description;
public string[] credits;
public string[] meta;
public string asset;
public FileInfo file;
public FileInfo icon;
public bool stereo;
public bool overUnder;
};
This is the function:
jsonAsset LoadSceneDataFromJSON(FileInfo jsonFile)
{
jsonAsset asset = new jsonAsset();
Debug.Log("Processing : " + jsonFile);
// Parse File for Data
var N = JSON.Parse(File.ReadAllText(jsonFile.FullName));
var cat_arr = N["categories"].AsArray;
asset.category = N["categories"]["name"].Value;
Debug.Log(N["categories"]["projects"]["assets"]["filename"].Value);
foreach (JSONNode n in cat_arr)
{
asset.project = n["name"].Value;
// Credits
var proj_credits = n["credits"].AsArray;
foreach (JSONNode pc in proj_credits)
{
asset.credits[asset.credits.Length] = pc["credits"].Value;
}
// Project Meta
var proj_meta = n["meta"].AsArray;
foreach (JSONNode pm in proj_meta)
{
asset.meta[asset.meta.Length] = pm["meta"].Value;
}
// Project Array
var proj_arr = n["projects"].AsArray;
foreach (JSONNode nn in proj_arr)
{
var asset_arr = nn["assets"].AsArray;
asset.asset = nn["assets"]["name"].Value;
foreach (JSONNode nnn in asset_arr)
{
asset.asset = nnn["name"].Value;
asset.file = new FileInfo(m_dir + nnn["filename"].Value);
asset.icon = new FileInfo(m_dir + nnn["icon"].Value);
var asset_meta = nnn["meta"].AsArray;
foreach (JSONNode am in asset_meta)
{
asset.meta[asset.meta.Length] = am.Value;
}
}
}
}
return asset;
}
You are treating projects as an object instead of an array.
I dont know what JSON library you are using to give you guidance, but something like this will probably work:
N["categories"]["projects"][0]["assets"]["filename"].Value
I tray to parse json with using Json.Net but i am new parsing json and i didn't get good result after so many test.
json structure is as below;
[
{
"Coo":{
"id":"1"
},
"Hor":{
"name":"Poo"
},
"Vor":{
"name":"Soo"
},
"Status":"1",
"Tola":[
{
"value":"10",
},
{
"value":"20",
}
],
"Opt":[
]
},
{
"Coo":{
"id":"2"
},
"Hor":{
"name":"Zoo"
},
"Vor":{
"name":"Koo"
},
"Status":"2",
"Tola":[
{
"value":"20",
},
{
"value":"10",
}
],
"Opt":[
]
},
{
"Coo":{
"id":"3"
},
"Hor":{
"name":"Moo"
},
"Vor":{
"name":"Noo"
},
"Status":"1",
"Tola":[
{
"value":"30",
},
{
"value":"20",
}
],
"Opt":[
]
}
]
My code is as below for parsing.
_JsonString = _JsonString.Trim().Trim('[',']');
JObject _JObject = JObject.Parse(_JsonString);
var _JItems = _JObject.SelectToken(".")
.Select(s => new
{
_Id = (string)s.SelectToken("Coo.id"),
_WhereClause = (string)s.SelectToken("Status")
})
.Where(w => w._WhereClause == "1");
foreach (var _JItem in _JItems)
{
MessageBox.Show(_JItem._Id.ToString());
}
Thank you in advance.
You are using JObject while you should use JArray:
Remove this line:
_JsonString = _JsonString.Trim().Trim('[', ']'); /*removed*/
And change
JObject _JObject = JObject.Parse(_JsonString);
To
JArray _JObject = JArray.Parse(_JsonString);
Full code:
JArray _JObject = JArray.Parse(_JsonString);
var _JItems = _JObject.SelectToken(".")
.Select(s => new
{
_Id = (string)s.SelectToken("Coo.id"),
_WhereClause = (string)s.SelectToken("Status")
})
.Where(w => w._WhereClause == "1");
foreach (var _JItem in _JItems)
{
MessageBox.Show(_JItem._Id.ToString());
}