JSON_ERROR_UTF8(5) error while json_decode - laravel

I am trying to read a JSON file that contains an array of objects located in laravel storage and trying to iterate it. My attempt is as below.
$json = Storage::disk('local')->get('users.json');
json_decode($json, true);
This will return string type for the $json. So I cannot iterate. Anyone knows where I got wrong and how can I fix it?
Below is the part of my $json output.
[
{
"_id": 1,
"url": "http://initech.tokoin.io.com/api/v2/users/1.json",
"external_id": "74341f74-9c79-49d5-9611-87ef9b6eb75f",
"name": "Francisca Rasmussen",
"alias": "Miss Coffey",
"created_at": "2016-04-15T05:19:46 -10:00",
"active": true,
"verified": true,
"shared": false,
"locale": "en-AU",
"timezone": "Sri Lanka",
"last_login_at": "2013-08-04T01:03:27 -10:00",
"email": "coffeyrasmussen#flotonic.com",
"phone": "8335-422-718",
"signature": "Don't Worry Be Happy!",
"organization_id": 119,
"tags": [
"Springville",
"Sutton",
"Hartsville/Hartley",
"Diaperville"
],
"suspended": true,
"role": "admin"
},
{...}
]
Edit: json_decode_error function returns 5 which is unsupported utf8 characters included in the file is the issue.

Handle json_decode error as follow using json_last_error.
if ($json === null && json_last_error() !== JSON_ERROR_NONE) {
echo "Incorrect json data.";
}
If you've unsupported UTF-8 characters in your encoded json then convert them before decoding.
$input = Storage::disk('local')->get('users.json');
$json = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($input));
$arr = json_decode($json, true);
If possible I suggest you to do the same while doing json_encode.

Related

Validation of each field in JSON response using karate API

I want to validate particular fields in the response whether it is integer or float(ex: fullbathrooms field). I tried below code but getting match failed error. Could you please help here ?.....Thanks
Given path '/property-client'
And request {"address": <address>,"city": <city>,"state": <state>,"zipCode": <zipCode>}
When method post
Then status 200
And print response
And match response == {fullbathrooms:'#number'}
Examples:
|read('testFile1.csv')|
Error : match failed: EQUALS
Actual response:
{
"success": true,
"message": {
"version": "1.0",
"response": {
"id": "94568859",
"type": "express",
"responseheader": null,
"reportdata": {
"property": {
"source": null,
"type": null,
"dom": null,
"propertytype": "Single Family Residence",
"standardtype": null,
"address": {
"documentid": null,
"number": "150",
"directional": null,
"street": "BRIDGE",
"suffix": "RD",
"postdirectional": null,
"unit": "",
"city": "HILLSBOROUGH",
"state": "CA",
"zip": "94010",
"zipplus4": "6908",
"fulladdress": "150 BRIDGE RD, HILLSBOROUGH, CA 94010"
},
"info": {
"type": null,
"fips": "6081",
"county": "San Mateo",
"bedrooms": "5",
"bathrooms": "6.50",
"fullbathrooms": "6.50",
"totalrooms": "0",
"livingarea": "7750",
"totallivingarea": "7750",
"landarea": "41382",
"landareatype": null,
"pool": "true",
"landvalue": "6904800",
"improvementvalue": "3284414",
"assessedvalue": "10189214",
"assessedyear": "2021",
"taxvalue": "11746898",
"taxyear": "2021",
"deliquentyear": null,
"yearbuilt": "2011",
"propertytax": null,
"approxage": "11",
"parcelnumber": "032-400-110",
"titlecompany": null,
"geocode": {
"latitude": "37.563272",
"longitude": "-122.334442",
"geoqualitycode": ""
}
}
Please take some time to read the documentation: https://github.com/karatelabs/karate#match-contains
I'm not going to refer to your response dump (which by the way is not valid JSON), but give you a simple example. Please pay attention to the structure of your JSON. And note that the 6.50 is a string not a number in your response.
* def response = { "foo": { "bar": { "fullbathrooms": "6.50" } } }
* match response.foo.bar == { fullbathrooms: '#string' }
If you want to validate numbers within strings, please refer other answers, for example: https://stackoverflow.com/search?q=%5Bkarate%5D+number+regex

Laravel data recording with API

I save the received data from the API to the database. In my API result, there is the following answer:
"opponents": [
{
"opponent": {
"acronym": "RH",
"id": 127276,
"image_url": "/image/127276/reverse_heaven_logo_std.png",
"location": null,
"modified_at": "2020-04-14T19:03:48Z",
"name": "Reverse Heaven",
"slug": "reverse-heaven"
},
"type": "Team"
},
{
"opponent": {
"acronym": " neon",
"id": 2061,
"image_url": "/image/2061/neon_esport.png",
"location": "PH",
"modified_at": "2020-04-14T19:04:02Z",
"name": "Neon Esports",
"slug": "neon-esports"
},
"type": "Team"
}
],
If i use var_dump($opponents), i receive only last opponent from API. How can I save exactly 2 values that are in the array under the same name opponent->name?
Since you are using laravel, you may use collections.
$decoded = json_decode($opponents);
return collect($decoded->opponents)->pluck('opponent.name')->toArray();
you may do it in a single line if you prefer;
return collect(json_decode($opponents)->opponents)->pluck('opponent.name')->toArray();
first decode the json like this
$decoded_opponents = json_decode($opponents);
then create a empty array
$array = [];
run a foreach loop on you decoded data
foreach($decoded_opponents->opponents as $key=>$value){
$array[]=$value->opponent->name;
}
the names now stored in $array

convert json array to json object in laravel 5.7

I am getting data from database using join query in laravel & pass to json and getting some result in array but I want object that I given below
Controller code:
$resultPastActivity= DB::table('table_user_create_activity')
->join('table_sub_category','table_user_create_activity.selected_activity_id', '=', 'table_sub_category.sub_category_id')
->select('sub_category_name','area','activity_type','activity_date','start_time','end_time')
->whereDate('activity_date', '<', $todayDate)
->where('user_id',$user_id)
->get();
return response()->json(['success' => '1','data' =>$resultPastActivity]);
The above code will give following json that is in array actually i want json in object
{
"success": "1",
"data": [
{
"sub_category_name": "Badminton",
"area": "Rankala lake",
"activity_type": "1",
"activity_date": "2018-01-12",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
{
"sub_category_name": "Football",
"area": "Devakar panad",
"activity_type": "1",
"activity_date": "2018-01-15",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
]
}
i want json as follows
{
"success": "1",
"data": {
{
"sub_category_name": "Badminton",
"area": "Rankala lake",
"activity_type": "1",
"activity_date": "2018-01-12",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
{
"sub_category_name": "Football",
"area": "Devakar panad",
"activity_type": "1",
"activity_date": "2018-01-15",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
}
}
try this, json_encode($json, JSON_FORCE_OBJECT) JSON_FORCE_OBJECT
$result=array();
$result["0"]=$resultPastActivity;
$json=json_encode((object)$result,JSON_FORCE_OBJECT);
return response()->json(['success' => '1','data' =>$json]);
The one you want is not a valid JSON, you can check it here: https://jsonformatter.curiousconcept.com/
So, you cannot create such an output, and, if you force it, the application that will receive it won't parse it correctly, so it doesn't make sense.

Error creating events with Microsoft graph

$p=array(
'subject'=>'Registrado desde iSchool',
'body'=>array(
'contentType'=>'HTML',
'content'=>'Evento de prueba',
),
'start'=>array(
'dateTime'=>'2017-05-28T12:00:00',
'timeZone'=>'Pacific Standard Time'
),
'end'=>array(
'dateTime'=>'2017-05-28T17:00:00',
'timeZone'=>'Pacific Standard Time'
),
'location'=>array('displayName'=>'Mi casa'),
'attendees'=>array(
'emailAddress'=>array('address'=>'email', 'name'=>'name'),
'type'=>'required'
),
);
$this->crear('calendars/'.$this->mg_model->idCalendarioUsuario().'/events', $p);
This function "$this->mg_model->idCalendarioUsuario()" Return the calendar ID
public function crear($objeto, $datos){
//$this->graph->setApiVersion("beta");
$r = $this->graph->createRequest("POST", "/me/$objeto")
//->addHeaders(array("Content-Type" => "application/json"))
->attachBody($datos)
->setReturnType(Event::class)
->execute();
}
Error: 400 Bad Request` response: { "error": { "code": "BadRequest", "message": "Property attendees in payload has a value that does not matc (truncated...)
What am I doing wrong?
The JSON payload for your example should look like this:
{
"subject": "Registrado desde iSchool",
"body": {
"contentType": "HTML",
"content": "Evento de prueba"
},
"start": {
"dateTime": "2017-05-28T12:00:00",
"timeZone": "Pacific Standard Time"
},
"end": {
"dateTime": "2017-05-28T17:00:00",
"timeZone": "Pacific Standard Time"
},
"location": {
"displayName": "Mi casa"
},
"attendees": [{
"emailAddress": {
"address": "email",
"name": "name"
},
"type": "required"
}]
}
Your attendees collection however is rendering as an object instead of an array. It is rendering your attendees as an object instead of an array. This is likely the cause of that payload error.
"attendees": {
"emailAddress": {
"address": "email",
"name": "name"
},
"type": "required"
}
Please note, I'm not a PHP expert so my code here may be rather inelegant. That said, I believe you can ensure it renders as an array by wrapping it in an additional array():
'attendees'=>array(array(
'emailAddress'=>array('address'=>'email', 'name'=>'name'),
'type'=>'required'
)),
Here is the PHP example:
"attendees" => [ array (
"emailAddress" => array(
"address" => "user#domain.com",
"name" => "User's first and last name",
),
"type" => "required",
)],

Parsing out multiple API JSON response parameters

I'm getting a JSON response back from an API, however the response has several key parameters all called 'jacket' with different values. I am able to parse out the first key but I don't get the rest of the values. Here is some of the code, I might be approaching this the wrong way:
parsed_list = JSON.parse(get_response.body)
orig = parsed_list["_links"]["stuff"]["orig"]
serv = parsed_list["_links"]["stuff"]["serv"]
puts orig.first["jacket"]
puts serv.first["jacket"]
=> 123456789
=> 987654321
This is what the JSON response looks like before I parse it out and set it "parsed_list"
"_links": {
"self": {
"href": "url"
},
"stuff": {
"href": "url",
"orig": [
{
"jacket": "123456789",
"Id": "x",
"selected": true,
}
],
"serv": [
{
"jacket": "987654321",
"Id": "xx",
"selected": false,
},
{
"jacket": "0000000001",
"Id": "xx",
"selected": false,
},
{
"jacket": "1111111110",
"Id": "xx",
"selected": false,
}
]
}
}
}
I need to be able to extract all of the "jacket" values.
The data's right there, you just need to get it:
serv.collect do |entry|
entry['jacket']
end

Resources