Adding base64 string to JSON invalidates it - json

I am creating a JSON Array having a byte64 string data. This is an invalid JSON but when I remove the displaypic value by some normal string the JSON is valid. Please help me with this. Is there any other way to work with images that has to be parsed on cross platforms. How do I deal with this byte 64 string.
It's a long data so can't add here.. The body limit is 30000. Please see this link for the JSON.
CODE THAT CREATES JSON
function checkLogin_post()
{
//$responsedata = array();
if($this->post('useremail') && $this->post('password'))
{
$useremail = $this->post('useremail');
$password = $this->post('password');
$this->load->model('loginmodel');
$table_data = $this->loginmodel->checkLogin($useremail);
if (sizeof($table_data) != 0)
{
foreach ($table_data as $data)
{
if($password == $data->password)
{
$responsedata["firstname"] = $data->firstname;
$responsedata["lastname"] = $data->lastname;
$responsedata["email"] = $data->email;
$responsedata["userid"] = $data->userid;
$responsedata["displaypic"] = $data->displaypic; //THIS IS THE BASE64
$responsedata["ispersonaldetailsfilled"] = $data->ispersonaldetailsfilled;
$responsedata["isexpertisedetailsfilled"] = $data->isexpertisedetailsfilled;
$responsedata["isprofessionaldetailsfilled"] = $data->isprofessionaldetailsfilled;
$this->response(array("success"=>$responsedata), 200);
//$this->response($responsedata, 200);
}
else
{
$this->response(array("error"=>"Password not matched"), 200);
}
}
}
else
{
$this->response(array("error"=>"User not found"), 200);
}
}
else
{
if($this->post('useremail') == "")
{
$this->response(array("error"=>"Useremail can't be null"),200);
}
if($this->post('password') == "")
{
$this->response(array("error"=>"Password can't be null"),200);
}
}
}

It was just missing a brace at the end. Here's your corrected JSON
Always use tools to validate your json before posting a question. I personally like http://pro.jsonlint.com

Related

Laravel modify collection value with another value of another collection

I have a json file like this,
{
"unique_id_001":{
"price_1":264000,
"price_2":2178000,
"price_3":3168000,
"price_6":1089000,
"price_7":3168000
},
"unique_id_002":{
"price_1":264000,
"price_2":2178000,
"price_3":3168000,
"price_6":1089000,
"price_7":3168000
},
"unique_id_003":{
"price_1":264000,
"price_2":2178000,
"price_3":3168000,
"price_6":1089000,
"price_7":3168000
}
}
I convert it to collection and want to set those price_x to another collection.
public static function getOldPrices()
{
$storagePath = storage_path(self::PATH);
$file = File::get($storagePath);
$data = json_decode($file, true);
$collection = \App\Price::hydrate($data);
$oldPrices = $collection->flatten();
return $oldPrices;
}
public static function all()
{
$prices = \App\Price::all();
$old_prices = self::getOldPrices();
foreach ($prices as $price) {
foreach ($old_prices as $old_price) { // is there another way so I can remove this loop?
if ($price->id === $old_price->id) {
$price->price_1 = $old_price->price_1;
$price->price_2 = $old_price->price_2;
$price->price_3 = $old_price->price_3;
$price->price_6 = $old_price->price_6;
$price->price_7 = $old_price->price_7;
}
}
}
return $prices;
}
This code is working and could change the value of each price in $prices. But I wonder if there is other ways, because I used two foreach loop in this code, and I think it is not good.
I got another way using map()
Here is my updated code
$prices = $prices->map(function ($price) use ($oldPrices) {
if ($oldPrice = $oldPrices->firstWhere('id', $price->id)) {
$price->price_1 = $oldPrice->price_1;
$price->price_2 = $oldPrice->price_2;
$price->price_3 = $oldPrice->price_3;
$price->price_6 = $oldPrice->price_6;
$price->price_7 = $oldPrice->price_7;
}
return $price;
});

Extract data from complex JSON in Flutter

I'm working in extract data from more complex JSON with unknown structure, its structure changes with operation ,
JSON sample link :http://afs-i.com/json.json
Kindly find my code here : http://afs-i.com/main.dart
Thanks in advance
Update:
I extracted the data using PHP code, you can find result here: http://afs-i.com/json.php
Kindly this is my PHP code:
$arraycars=array();
$y=json_decode($x);
// echo "<pre>";
// var_dump($y->tree[0]->children);
foreach ($y->tree[0]->children as $f) {
if(isset($f->vid)){
global $arraycars;
$arraycars[]=$f;
} elseif(isset($f->children)){
if(sizeof($f->children) > 0){
coolectcars($f->children);
}
}
}
function coolectcars($array){
// var_dump($array);
foreach ($array as $f) {
if(isset($f->vid)){
global $arraycars;
$arraycars[]=$f;
} elseif(isset($f->children)){
if(sizeof($f->children) > 0){
coolectcars($f->children);
}
}
}
}
echo json_encode($arraycars);
Update:2
I have problem now with null error for this code:
The error:
I/flutter ( 4264): NoSuchMethodError: The method 'forEach' was called on
null.
I/flutter ( 4264): Receiver: null
I/flutter ( 4264): Tried calling: forEach(Closure: (Children) => Null)
The code:
List<Children> cars = [];
Queue numQ = new Queue();
numQ.addAll(parsed["tree"][0]["children"]);
Iterator i = numQ.iterator;
while (i.moveNext()) {
// print("ddddddd ${i.current}");
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'], i.current['protocol'], i.current['datetime'],
i.current['gpss']));
} else {
Queue numQ = new Queue();
if (i.current["children"] != null) {
numQ.addAll(i.current["children"]);
// iterate(numQ);
List<Children> carse=[];
carse = iterate(numQ);
carse.forEach((data){
cars.add(data);
}) ;
}
}
}
cars.forEach((data) {
print(data.toString());
});
List<Children> iterate(Queue numQ) {
List<Children> cars=new List<Children>();
Iterator i = numQ.iterator;
while (i.moveNext()) {
print("ddddddd ${i.current}");
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'], i.current['protocol'], i.current['datetime'],
i.current['gpss']));
} else {
if (i.current["children"] != null) {
Queue numQ = new Queue();
numQ.addAll(i.current["children"]);
List<Children> carse=[];
carse = iterate(numQ);
carse.forEach((data){
cars.add(data);
}) ;
}
}
return cars;
}
}
I prefer using built_value to do json deserialization/ serialization. It's more elegant. You don't need to write down fromJson by yourself. built_value will generate deserializers / serializer for you. You can check built_value's github or this and this articles.
A good place for convert JSON to dart here
hats to reddit url
just copy your json into the textbox and generate, it will auto generate for you.
With this, you can call fromJson and feed it the json, then you can also get auto complete for it
eg: usage
final response =
await http.get('http://afs-i.com/json.json');
if (response.statusCode == 200) {
final Autogenerated respJson = Autogenerated.fromJson(json.decode(response.body));
print(respJson.tree[0].userId);
}
insert this import 'dart:convert';
into your widget file at top.
lets say you have your json in
var response
then
var jsonDecoded= json.decode(response);
now you can get name and user_id like this:
var user_id= jsonDecoded["tree"][0]["user_id"];
var name = jsonDecoded["tree"][0]["name"];
NOTE : I get these values from the first object (0 index). If you want values for each object , you can loop to get it.
The final answer i reach:
final parsed = json.decode(response.body);
List<Children> cars = [];
Queue numQ = new Queue();
numQ.addAll(parsed["tree"][0]["children"]);
Iterator i = numQ.iterator;
while (i.moveNext()) {
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'],
i.current['datetime'],
));
} else {
Queue numQ = new Queue();
if (i.current["children"].toString() != "[]") {
numQ.addAll(i.current["children"]);
List<Children> carse = [];
carse = iterate(numQ);
carse.forEach((data) {
cars.add(data);
});
}
}
}
List<Children> iterate(Queue numQ) {
List<Children> cars = new List<Children>();
Iterator i = numQ.iterator;
while (i.moveNext()) {
if (i.current.containsKey("vid")) {
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'],
i.current['datetime'],
));
}
} else {
if (i.current["children"].toString() != "[]") {
Queue numQ = new Queue();
if (i.current["children"].toString() != "[]") {
numQ.addAll(i.current["children"]);
List<Children> carse = [];
carse = iterate(numQ);
carse.forEach((data) {
cars.add(data);
});
}
}
}
return cars;
}

Laravel "Malformed UTF-8 characters, possibly incorrectly encoded", how to fix?

I try to return as json added attribute which I get with the following method in my User model but I keep getting
"message": "Malformed UTF-8 characters, possibly incorrectly encoded",
"exception": "InvalidArgumentException",
"file": "/var/www/timetool/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php",
the code
/**
* #return string
*/
public function getAvatarImageAttribute($value)
{
if($this->hasMedia('avatar')) {
$image = $this->getMedia('avatar');
$img = \Intervention\Image\ImageManagerStatic::make($image[0]->getPath())->encode('data-url');
}
elseif (isset($this->blob->dokument)) {
$img = 'data:image/jpeg;base64,'. base64_encode($this->blob->document);
} else {
$img = '';
}
return $img;
}
in controller I have
return \Response::json($users, 200, array('Content-Type' => 'application/json;charset=utf8'), JSON_UNESCAPED_UNICODE);
I'm thinking it's related to JSON needing only UTF8 chars and your blob may have invalid chars. Try utf8_encode($img). http://at2.php.net/manual/en/function.utf8-encode.php
In your controller just return. Laravel will build a proper json response for you.
Paste this function top of your document:
public static function convert_from_latin1_to_utf8_recursively($dat)
{
if (is_string($dat)) {
return utf8_encode($dat);
} elseif (is_array($dat)) {
$ret = [];
foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);
return $ret;
} elseif (is_object($dat)) {
foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);
return $dat;
} else {
return $dat;
}
}
Call the above function to convert the content. It has a parameter just it need the value of blob image (binary):
$img = $this->convert_from_latin1_to_utf8_recursively($this->blob->document)
In my case the problem was the encoding of the controller. The solution was to convert it to UTF8 and the bug was fixed.

How to properly create an array of JSON objects in Typescript?

I'm trying to create an array of JSON objects in typescript. And following is the approach I have used.
var queryMutations:any = _.uniq(_.map(mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
var item = {facet: "MUTATION", term: mutation.gene + " " + mutation.proteinChange}
return item;
}
else {
return {};
}
}));
var jsonString = JSON.stringify(queryMutations);
is this the correct way to do it? Appreciate your suggestions.
To me it looks ok. I'd personally make a few layout style modifications and use backtick placeholder strings.
var queryMutations:any =
_.uniq(
_.map(
mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
return {facet: "MUTATION",
term: `${mutation.gene} ${mutation.proteinChange}`
} else {
return {};
}
}
)
);
var jsonString = JSON.stringify(queryMutations);

Handling Inconsistent Delimiters in Flat File Source on ForeachLoop Container

I'm trying to handle inconsistent delimiters in 'n Flat File Source contained in a Data Flow Task running in a Foreach Loop container in SSIS.
I have several files in a folder with varying names but with one consistent identifier e.g.
File23998723.txt
File39872397.txt
File29387234.txt etc., etc.
These files, as a standard should be tab delimited, but every so often a user missed cleaning up a file and it will be delimited with a , or a ; etc., which causes the package import to fail.
Is there an easy approach for me to follow to dynamically change the delimiter or to test for the delimiter beforehand?
I managed to handle it with a script task, thanks!
Basically added a script task to the Foreach Loop Container that executes before my DataFlow task.
I send the file name through as a variable:
I added the following namespaces to the script:
using System.IO;
using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;
And my script looks like this:
public void Main()
{
if (!string.IsNullOrEmpty(Dts.Variables["sFileName"].Value.ToString()))
{
StreamReader file = new StreamReader(Dts.Variables["sFileName"].Value.ToString());
if (file != null)
{
string HeadRowDelimiter = "";
string ColDelimiter = "";
string data = "";
while (file.Peek() >= -1)
{
char[] c = new char[500];
file.Read(c, 0, c.Length);
data = string.Join("", c);
if (!string.IsNullOrEmpty(data))
{
//set row delimiters
if (data.Contains("\r\n"))
{
HeadRowDelimiter = "\r\n";
}
else if (data.Contains("\r"))
{
HeadRowDelimiter = "\r";
}
else if (data.Contains("\n"))
{
HeadRowDelimiter = "\n";
}
else if (data.Contains("\0"))
{
HeadRowDelimiter = "\0";
}
//set column delimiters
if (data.Contains("\t"))
{
ColDelimiter = "\t";
}
else if (data.Contains(";"))
{
ColDelimiter = ";";
}
else if (data.Contains(","))
{
ColDelimiter = ",";
}
else if (data.Contains(":"))
{
ColDelimiter = ":";
}
else if (data.Contains("|"))
{
ColDelimiter = "|";
}
else if (data.Contains("\0"))
{
ColDelimiter = "\0";
}
}
break;
}
file.Close();
RuntimeWrapper.IDTSConnectionManagerFlatFile100 flatFileConnection = Dts.Connections["FlatFileConnection"].InnerObject as RuntimeWrapper.IDTSConnectionManagerFlatFile100;
if (flatFileConnection != null)
{
flatFileConnection.HeaderRowDelimiter = HeadRowDelimiter;
flatFileConnection.RowDelimiter = HeadRowDelimiter;
flatFileConnection.HeaderRowsToSkip = 0;
flatFileConnection.Columns[0].ColumnDelimiter = ColDelimiter;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}