Dart/Flutter : Avoid Method parsing in Map , when converting to JSON? - json

In Dart / Flutter , when converting a map (which contains a Closure method) to json using jsonEncode , I getting following error :
Converting object to an encodable object failed: Closure: () => dynamic
The Map having :
orderedMap1["fooddelete"] = () => deleteItemFunction(
singleitem["orderId"], singleitem["id"], singleitem["shopId"]);
If commented above line , then jsonEncode works , else throwing above error .
How to instruct the jsonEncode to skip the closures when parsing Map to Json ?

It seems highly questionable to store closures in the same Map that you want to encode to JSON, but if you must, you can encode a filtered copy of it instead:
var encoded = jsonEncode({
for (var entry in orderedMap1.entries)
if (entry.value is! Function) entry.key: entry.value,
});
I suppose you alternatively could use jsonEncode's toEncodable parameter to convert closures to something else, although I'm not sure what good that would do you since there's nothing the recipient could do with it. The following will replace closures with null:
var encoded = jsonEncode(orderedMap, toEncodable: (value) {
if (value is Function) {
return null;
}
throw UnsupportedError('Cannot convert to JSON: $value');
});

option1: remove "fooddelete" key using orderedMap1.remove("fooddelete") and then parse it.
option2: put your Closure inside the double quotation. so you can save it as String.

Related

How to parse "streamed" json objects with json4s?

I have a streaming source that produces many JSON objects without separators (or only whitespace in between). If I pass that to json4s parse function, it only produces AST for the first object.
As a workaround, I could parse it manually and either turn it into a JSON array by adding brackets and commas as appropriate or chunk it and call parse on each chunk.
However, this is a rather common format, so I'm sure the problem is already solved. I just cannot find the API for it in json4s documentation.
If you reading it from an InputStream, then use BufferedInputStream wrapper with mark(), read() and reset() calls to skip whitespace(s) between parse() call:
val in = new BufferedInputStream(new FileInputStream("/tmp/your.json"))
try {
var continue = true
in.mark(1)
do {
in.reset()
// <-- here should be call for parse
// skip white spaces or exit if EOF found
var b = 0
do {
in.mark(1)
b = in.read()
if (b < 0) continue = false
} while (Character.isWhitespace(b))
} while (continue)
} finally in.close()
EDIT: Today I have released 0.11.0 version of jsoniter-scala with new ability to parse streaming JSON values or JSON arrays w/o need to hold all values in memory.

Asserting entire response body in post man

I recently started working on spring boot projects.
I am looking for a way to assert the entire response of my API.
The intention of this is to reduce the testing time taken for the API.
Found A few solutions mentioned below, but nothing helped me resolve the issue.
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
When I put the entire response body as an argument, I get the below errors.
Unclosed String
2.
3.
If you want to use the same type of quotes you defined the string with inside it, you have to escape them:
'string with "quotes"'
"string with 'quotes'"
'string with \'quotes\''
"string with \"quotes\""
You probably want to put your json in single quotes as they are not allowed by json itself.
You could try setting the response as a variable and then assert against that?
var jsonData = pm.response.json()
pm.environment.set('responseData', JSON.stringify(jsonData))
From here you can get the data JSON.parse(pm.enviroment.get('responseData')) and then use this within any test to assert against all of the values.
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData).to.deep.equal(JSON.parse(pm.environment.get('responseData')))
})
My reasoning is that you’re trying to assert against JSON anyway but doing as a plain text string.
Or you could assert against the values separately like this:
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData[0].employeeName).to.equal("tushar")
pm.expect(jsonData[0].phNum).to.equal(10101010)
})
Depending on the JSON structure you may not need to access an array of data and the [0] can be dropped.

parsing and applying conditional element on key value pair in typescript

I am doing an Ionic App with typescript.
I have some error condition as response from REST API,
I did
err._body
and it gives me
{"reason":"invalid_token"}
but when I do
err._body.reason
or
err._body.get("reason")
it gives undefined value.
I did JSON stringify and parse as well, no luck,
How to parse this and get the value so that I can apply specific processing for this.
First try to do
console.log(typeof err._body);
so we can be sure what the type of that is. If it's a string, you should do
let errorObj = JSON.parse(err._body);
// And then...
let errorMsg = errorObj.reason // or errorObj["reason"] as well
If it's an Object, you can skip the parse() part and just use it like this:
let errorMsg = err._body.reason // or err._body["reason"]

cordova readAsText returns json string that can't be parsed to JSON object

I read my json file using http and cordova file readAsText functions.
http request returns an object which is ok.
cordova file readAsText function return 'string' which contain extra "r\n\" symbols. This make it impossible to use JSON.parse(evt.target.result)
function readJson(absPath, success, failed){
window.resolveLocalFileSystemURL(absPath, function (entry) {
entry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
success(evt.target.result);
};
reader.readAsText(file);
}, failed);
}, failed);
}
readJson(cordova.file.dataDirectory + 'my.json', function(res){
console.log(JSON.parse(res)); //here I've got an parsing error due to presence of r\n\ symbols
}, failed );
How to read JSON files using cordova?
UPDATE:
funny thing that the following works:
a = '{\r\n"a":"1",\r\n"b":"2"\r\n}';
b = JSON.parse(a);
so the problem not only with \r\n... there is something else that is added by cordova readAsText
UPDATE2
as a workaround I use now var object = eval("(" + res + ")")
Still search for a common way to load json objects...
No one has answered this and I just had to solve it for my project, so I will post my solution.
The readAsText method outputs a string, so you CAN actually run a replace on it, but what you need to do is use a RegExp to find the newline character. here's my solution:
var sanitizerRegex = new RegExp(String.fromCharCode(10), 'g');
var sanitizedData = JSON.parse(result.replace(sanitizerRegex, ''));
I've used the String method fromCharCode to get the specific newline character and the "g" flag to match all instances in the entire string. The problem with your string solution is that you can't do a string replace using the characters for backslash and "n" because the issue is the actual new line character, which is merely represented as "\n".
I do not know the reason JSON.parse can't handle the newline character, or why the file plugin introduces this problem, but this solution seems to work for me.
Also, NEVER use eval like this if you can avoid it, especially on input from a source like a JSON file. Even in a cordova app, using eval is potentially very unsafe.
I found out the solution after debug deeply. readAsText function returned text has one more letter at the first position of text.
Example:
{"name":"John"} => ?{"name":"John"} (?: API didn't return ?, just one string)
I confirmed this with length of result, so we need to use substr(1) before parse JSON.
fileContent = fileContent.substr(1);
var jData = jQuery.parseJSON(fileContent);

Convert JSON object to array?

I have this on my console on firebug,
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...}, Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
it is data from the server side. Now, how would I convert this into array such that this data can be used on another file. I tried JSON.parse and jQuery.parseJSON but both did not work.
That isn't JSON it's a Javascript array of objects, not a string. My guess is that you've received this from a jQuery ajax call and you had the dataType : 'json' set so that jQuery has automatically parsed the JSON into this array.
To send it to a PHP script you can convert it back to JSON using:
var myString = JSON.stringify(data);
and then fire off an ajax call to the PHP script with that as the POST data:
var myString = JSON.stringify(data);
$.post('page.php', { data : myString }, function(){
console.log( "sent" );
});
In PHP you can decode it using:
$data = json_decode($_POST['data']); // <-- or whatever your post variable is named
foreach($data as $obj)
{
echo $obj->fa_id;
}
if you want to get an php array use this
http://php.net/manual/en/function.json-decode.php
The string you provided is not valid JSON.
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...},
Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
In particular, the "Object" and "more..." strings cannot be interpreted by a JSON parser.
Assuming the object you are inspecting is a variable named foo:
console.log(JSON.stringify(foo));
Should print a valid JSON representation of your object to the Javascript console.