Our application uses json files for configuration.
If the file has configuration data we parse it and all goes well.
If the file has bad data [{ asdf 34453 %^$% dfgdsf }] we handle just fine
If the config file is missing then we handle that.
The scenario I'm trying to figure out is if it is an empty object such as [{}] I'm looking for a reliable way by checking the first Xnode, last Xnode, Xattribute..something because HasElements will return true for an empty object.
Please don't suggest using 3rd part libraries etc. Not happening as decided by others.
The code I am using:
private static bool TryParseJson(MemoryStream msJson)
{
bool IsValid = false;
XElement root;
XmlReader xReader = JsonReaderWriterFactory.CreateJsonReader(msJson, new XmlDictionaryReaderQuotas());
//an empty json file ( [] ) will parse but have no elements hence the elements check.
//a file full of giberish...incorrect json format will fail to parse and throw exception hence the try catch
try
{
root = XElement.Load(xReader);
}
catch
{
return IsValid;
}
//an empty file ( [{}] will return positive for HasElements so we also get ?????
XNode ???? = root.FirstNode;
if (root.HasElements && !???)
{
IsValid = true;
return IsValid;
}
return IsValid;
}
I think I have found a way to handle an empty object. My testing with valid json and empty json shows that an empty object [{}] will still return a single element but there will be NO nodes in that element so I went with this:
//an empty file ( [{}] will return positive for HasElements so we also get
bool IsEmptyObject = (root.Elements().Nodes().Count() > 0) ? true : false;
I'd still be interested in hearing the contributions of others.
Thanks
Related
I am trying to pull out the value "533"
{
"d": {
"ItemValue_1": 533
},
"ts": "2021-01-20T10:59:41.958591"
}
This does not work
var ItemValue_1 = msg.payload.ItemValue_1;
msg.payload = ItemValue_1;
return msg;
My result is unsuccessful
I was able to solve on my own, it works.
sensorMeasurement=JSON.parse(msg.payload);
msg.payload=sensorMeasurement.d;
var msgout = {payload : msg.payload.ItemValue_1}
return msgout;
The better way to do this is as follows:
Add a JSON node before the function node, this will turn a string payload in to a JSON object (assuming the string actually represents a JSON object).
Then if you are using a function node the following:
msg.payload = msg.payload.d.ItemValue_1;
return msg;
It is bad practice to create a new object as you did in your answer as it throws away any meta data that may be required later that is attached to the original object.
Rather than use a function node it would also be cleaner to use a change node and the Move mode to shift the msg.payload.d.ItemValue_1 to msg.payload
Mostly this is about just sending hard coded JSON from Web API method back to a caller app ( happens to be React). My current action looks something like the following:
[Route("members/{memberId}")]
public async Task<IActionResult> Members(string memberId)
{
// {
// "SecA4": ["Asian"]
// }
// ?? string json = "{ \"SecA4\": [\"Asian\"] }"; //??
return OK() // need to place JSON in the OK() method. but how should it be done?
}
So currently I am able to load from a file into a survey engine a file that looks like that. Thus I load from a .json file.
{
"SecA4": ["Asian"]
}
Rather then a hard-coded string I would use an object rather, which would be done something like the following
object someObject = new
{
SecA4 = "Asian"
};
You can create this pretty much the same way as you would do with Json.
Now we are just returning the newly created object and converting it into Json.
return Json(someObject, new JsonSerializerSettings() { Formatting = Formatting.None });
Where in the JsonSerializerSettings you can tell Newtonsoft.Json to no use any formatting e.g. new lines, spaces and so on.
I am new to flutter and dart I read a lot of web article and documentation but didn't able to figure out how to update JSON field I have a local JSON file like
{
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}]}
I want to update the filed favorite to true in JSON file Is there any way to do this
You Can parse the JSON like this
Map<String, dynamic> data = jsonDecode(jsonString);
And if you want to make each favorite true then You can use looping like this
(data["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);
if you want to set a single object value true then you need to pass the position like this
(data["quotes"] as List<dynamic>)[position]['favorite'] = true;
Addition
Here is the link to encode and decode the JSON
You can use a forEach loop on the quotes list in the JSON and set favourite to true inside it. I'm assuming you have a parsed your String data into JSON using jsonDecode or json.decode.
If not, here's a link on how to parse JSON data in Dart.
Consider the below code -
Map<String, dynamic> jsonData = {
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}
]};
(jsonData["quotes"] as List<dynamic>).forEach((item) {
item["favorite"] = true;
});
You can also alternatively use shorthand syntax for the forEach loop function like below -
(jsonData["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);
first take this json array to any variable and then understand the hierarchy .
e.g "jsonArr" is the array that hold that data then ..
jsonArr['quotes'][0]['favorite'] = true;
or you can put this in a for loop and traverse this loop to the length of the json array.
You can use the following method. The field favorite is changed to true when the button is pressed.
FlatButton(
child: Text('Add Favourite'),
onPressed: (){
myJson['quotes'][myIndex]['favorite'] = true;
})
I recently upgraded to PHP 7.0.4 and nginx 1.8.1, my application uses the Zend Framework (Magento 1.9.2.1). Since that upgrade, our customers sometimes get an "Decoding failed: Syntax error" when submitting an orderm which is thrown in
public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
{
$encodedValue = (string) $encodedValue;
if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
$decode = json_decode($encodedValue, $objectDecodeType);
// php < 5.3
if (!function_exists('json_last_error')) {
if (strtolower($encodedValue) === 'null') {
return null;
} elseif ($decode === null) {
#require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Decoding failed');
}
// php >= 5.3
} elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
#require_once 'Zend/Json/Exception.php';
switch ($jsonLastErr) {
case JSON_ERROR_DEPTH:
throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
case JSON_ERROR_CTRL_CHAR:
throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
case JSON_ERROR_SYNTAX:
throw new Zend_Json_Exception('Decoding failed: Syntax error');
default:
throw new Zend_Json_Exception('Decoding failed');
}
}
return $decode;
}
I read about a bug that PHP7 and JSON decode behaves differently when encoding an empty string. Does anyone know if this bug is related to PHP7 or to my application/server?
Thanks
This is an absolutely normal behaviour of json_decode.
It will throw this exception if the given string is not a valid JSON String.
As you already mentioned, an empty string is also not a valid JSON String.
json_decode('Hello') // invalid
json_decode("Hello") //invalid
But:
json_decode("'Hello'") // valid JSON string
Empty strings will raise an exception since PHP7!
"Calling json_decode with 1st argument equal to empty PHP string or value that after casting to string is empty string (NULL, FALSE) results in JSON syntax error."
So... to answer your question: In my opinion, your application has the problem you need to solve, if downgrading your PHP version is not an option.
The Magenta function needs to check for a valid representation of a JSON string BEFORE passing it to the json_decode function.
Try to set the variable to {} if it is not a string (is_string) or if it is empty.
If this is not the problem, it might be possible that your string is not encoded as it should be. Many times encoding of the strings passed to json_decode will result into that exception also.
One possible (dirty) fix is to set the build in decoder of Zend to true, while this may be much slower this does work on PHP7 where the default package errors out.
in class Zend_Json, set $useBuiltinEncoderDecoder to true;
public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
{
$encodedValue = (string) $encodedValue;
if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
This way the return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType); will be used which seems to be working just fine.
Dirty hack:
In my case it was a problem in Magento 2.2 with PHP7 where an empty object would throw an error. It would prevent the product indexer from completing.
So I added an empty array return for this case (in file vendor/magento/zendframework1/library/Zend/Json.php):
public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
{
$encodedValue = (string) $encodedValue;
if($encodedValue == "a:0:{}") { return []; } //<- added: return an empty array
if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
....
I have the same problem. I have a temporary fix as follows, waiting for a better solution
//return Zend_Json::decode($data->params);
return json_decode($data->params);
This was fixed in zend-mvc 3.1.1
JObject.Parse(jsonString) is causing issue for boolean data. e.g. The json is :
{
"BoolParam": true
}
I used the following code to parse:
JObject data = JObject.Parse(str1);
foreach (var x in data)
{
string name = x.Key;
Console.Write(name + " (");
JToken value = x.Value;
Console.Write(value.Type + ")\n");
Console.WriteLine(value);
}
This print out the value as :
BoolParam (Boolean) : True
The case sensitivity causes issue as I save this json for later use. The saved json looks like
{
"BoolParam": True
}
However, when i later use it, the JObject.Parse(str) throws error as invalid Json :Unexpected character encountered while parsing value: T. Path 'BoolParam', line 2, position 15.
If I change the case from "True" to "true", it works. I dont want to add this hack to change the case when saving but is there a better way to handle this scenario.
I dont want to add this hack to change the case when saving but is
there a better way to handle this scenario.
No, you have to produce valid JSON when saving if you want to be able to later deserialize it with a JSON serializer such as Newtonsoft JSON. So fixing your saving routing is the right way to go here.
One could use anonymous types and no worry about case sensitivity of boolean type variables
public static void Main()
{
bool a = true;
JObject c = JObject.FromObject(new {BoolParam= a});
Console.WriteLine(c);
}
Output:
{
"BoolParam": true
}