JSON : Accessing (editing) value using dynamic key - json

I have a JSON Object which looks like :
{ "stepbystep": { "steps": { },
"step1": "This is a step"
}
}
I need to edit the value of "step1" using a function.
My function is
function editJSON(parsedJSON,key) // parsedJSON is the JSONObject,key = "stepbystep.step1"
{
parsedJSON[key] = "This is now step 1";
}
How do I access inner/deep values using dynamic keys ?

Access your json like this :
// $js has json
$response = json_decode($js,true);
$stepbystep=$response["stepbystep"];
foreach($stepbystep_arr AS $stepbystep_obj)
{
echo $stepbystep_obj['step1'];// here is your desired value
//if you want dynamic step1, step2... you can use for loop
//$n is count
for($i=1;$i<=$n;$i++)
{
$stepbystep_obj['step'.$i];
}
}

Related

Newtonsoft.json SelectToken Replace differs from SelectTokens Replace in foreach with a NullReferenceException

Hope anybody could guide me here. I spend some hours on it and can't understand what's going on.
Mission: Replace a json element by a jsonpath search tag. (sort of $ref feature)
In my code example below i want to replace the value of DataReaderUser by a value found by the json path search $.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username . In this case it should result in the value "contoso\SVCSCOM-DO-OMDAS"
The code below works as expected.. the issue is below this code ..
https://dotnetfiddle.net/gEjggK
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{
""SQLServer"": {
""SQLReportingServices"": {
""AccountSettings"": {
""DataReaderUser"": {""$JsonPath"": ""$.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username""},
}
}
},
""UsersAndGroups"": {
""Users"": [
{
""Name"": ""OMActionAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
},
{
""Name"": ""OMDASAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
}
]
}
}";
JObject jo = JObject.Parse(json);
var JsonPath = jo.SelectToken("..$JsonPath");
JsonPath.Parent.Parent.Replace(jo.SelectToken(JsonPath.ToString()));
Console.WriteLine(jo.ToString());
}
}
The output will be :
{
"SQLServer": {
"SQLReportingServices": {
"AccountSettings": {
"DataReaderUser": "contoso\\SVCSCOM-DO-OMDAS"
}
}
},
"UsersAndGroups": {
"Users": [
{
"Name": "OMActionAccountUser",
"Username": "contoso\\SVCSCOM-DO-OMDAS"
},
{
"Name": "OMDASAccountUser",
"Username": "contoso\\SVCSCOM-DO-OMDAS"
}
]
}
}
Now the issue:
I want to do the same for all possible jsonpaths refers. So i use the SelectTokens and an foreach . But it looks like the behavior is different , the parents are null.
https://dotnetfiddle.net/lZW3XP
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{
""SQLServer"": {
""SQLReportingServices"": {
""AccountSettings"": {
""DataReaderUser"": {""$JsonPath"": ""$.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username""},
}
}
},
""UsersAndGroups"": {
""Users"": [
{
""Name"": ""OMActionAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
},
{
""Name"": ""OMDASAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
}
]
}
}";
JObject jo = JObject.Parse(json);
var JsonPaths = jo.SelectTokens("..$JsonPath");
foreach (var JsonPath in JsonPaths )
{
JsonPath.Parent.Parent.Replace(jo.SelectToken(JsonPath.ToString()));
}
Console.WriteLine(jo.ToString());
}
}
And the output:
Run-time exception (line 34): Object reference not set to an instance of an object.
Stack Trace:
[System.NullReferenceException: Object reference not set to an instance of an object.]
at Newtonsoft.Json.Linq.JsonPath.PathFilter.GetNextScanValue(JToken originalParent, JToken container, JToken value)
at Newtonsoft.Json.Linq.JsonPath.ScanFilter.<ExecuteFilter>d__4.MoveNext()
at Program.Main() :line 34
would be great to get some directions since i am spinning my head here.
michel
SelectTokens uses lazy evaluation and if you modify the token while enumerating all matches it can break in unexpected ways. A simple fix is to add ToArray() to force eager evaluation:
var JsonPaths = jo.SelectTokens("..$JsonPath").ToArray();

get json root key based on value

{
"vitals": {
"title": "Vitals IR",
"name": "vitalsIr",
"formid":"5ed5f7ca158a91827891cab2"
},
"anthropometry": {
"title": "Anthropometry IR",
"name": "anthropometryIr",
"formid":"5ed621ac158a91228191cafd"
}}
How to get the root key name vitals , anthropometry based on formid value
for example if formid value is "5ed621ac158a91228191cafd"
I need output as anthropometry need to achieve this in angular javascript
To loop through a json object using JavaScript, you can preform a for on the keys. E.g for (jsonPropertyName in json) { ... }. You can then query the formId.
For example:
function ProvideRootKey(formId) {
var results;
for (jsonPropertyName in json) {
if (json[jsonPropertyName]['formid'] === formId) {
results = jsonPropertyName
}
}
return results
}
var json = JSON.parse('{ "vitals":{ "title":"Vitals IR", "name":"vitalsIr","formid":"5ed5f7ca158a91827891cab2"}, "anthropometry":{ "title":"Anthropometry IR", "name":"anthropometryIr", "formid":"5ed621ac158a91228191cafd"}}');
console.log(ProvideRootKey('5ed621ac158a91228191cafd'))
Output (in console log):
"anthropometry"
See working example: https://jsfiddle.net/vgo81stm/1/

How to access data inside a complex JSON object in Dart?

I use a WebSocket to communicate to a server in my Flutter app. Let's say I receive a JSON object trough the WebSocket :
{
"action": "getProduct",
"cbackid": 1521474231306,
"datas": {
"product": {
"Actif": 1,
"AfficheQte": 0,
"Article": "6"
},
"result": "success"
},
"deviceID": "4340a8fdc126bb59"
}
I have no idea what the content of datas will be until I read the action, and even then, it's not guaranteed to be the same every time. One example of a changing action/datas is when the product doesn't exist.
I can parse it in a Map<String, Object>, but then, how do I access what's inside the Object?
What's the correct way to read this data?
Not sure what the question is about, but you can check the type of the values and then continue accordingly
if(json['action'] == 'getProduct') {
var datas = json['datas'];
if(datas is List) {
var items = datas as List;
for(var item in items) {
print('list item: $item');
}
} else if (datas is Map) {
var items = datas as Map;
for(var key in items.keys) {
print('map item: $key, ${items[key]}');
}
} else if(datas is String) {
print('datas: $datas');
} // ... similar for all other possible types like `int`, `double`, `bool`, ...
}
You also can make that recursive to check list or map values if they are String, ...

Taking out a text from a String as a Key from Json

I need to take out 1000 from this Key-Value Pair in node Js
"msg":"amamm : ErrorResponse {\"abcd1\":{\"Status\":\"E\",\"rem\":{\"Code\":\"1000\",\"message\":\"Unable to access your information at this time.(1000)\"}}}"
The JSON what you have posted is invalid. May be your JSON should be like the following:
var json = {
"msg": {
"amm": {
"ErrorResponse": {
"abcd1": {
"Status": "E",
"rem": {
"Code": "1000",
"message": "Unabletoaccessyourinformationatthistime.(1000)"
}
}
}
}
}
}
Then in node.js you have get the value using dot notation like as follows:
json.msg.amm.ErrorResponse.abcd1.rem.code
Will give you the value 1000
Assuming you can get the string
amamm : ErrorResponse {\"abcd1\":{\"Status\":\"E\",\"rem\":{\"Code\":\"1000\",\"message\":\"Unable to access your information at this time.(1000)\"}}}
by doing err.msg
You can get the json and then get the string you want. I copied the content of the msg into a variable str just to test the regex
var re = /\{.*?\}$/;
var str = 'amamm : ErrorResponse {\"abcd1\":{\"Status\":\"E\",\"rem\":{\"Code\":\"1000\",\"message\":\"Unable to access your information at this time.(1000)\"}}}';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
var content = JSON.parse(m[0]);
console.log(content);
console.log(content.abcd1.rem.Code);
}
Here's a working example: http://jsfiddle.net/sger1gk6/

How to Parse this Json with Json.net?

I have this json:
{
"Message": "The request is invalid.",
"ModelState": {
"Email": [
"The Email field is required."
]
}
}
I want to find the ModelState(if it exists) and then loop through all the errors that re in there.
I can figure out how to do this. I don't want to make a concrete class as the data might change depending on what happens on the sever.
I also can use dynamic as I am on WPF7
JObject jsonObj = JObject.Parse(response.Content);
foreach (var j in jsonObj)
{
var t = j.Value;
}
this is what I have so far.
JObject jsonObj = JObject.Parse(response.Content);
var modelState = jsonObj["ModelState"];
if (modelState != null)
{
// The JSON contains a property called ModelState
// so we can start looping through it:
foreach (JProperty item in modelState)
{
Console.WriteLine(item.Name);
foreach (JValue error in item.Values())
{
Console.WriteLine(error);
}
}
}