Checking the first element of json - json

I am very new to Json and need to access elements of json:
$users=User::all()->toJson();
print_r($users[0]) gives only [
and print_r($users[0]->email) gives me the error trying to get property of non object.
$users[0]["email"] gives Illegal string offset 'email'.
$users[0].email Use of undefined constant name - assumed 'email'
How do i get the name of first user?

it acts like a string so it shows only [ while $user[0].. don't use toJson()
$users = User::all();
$email = $users[0]->email;
is enough. to get the value from the array.

Related

laravel-translatable: converting existing text column to translatable

i'm trying to convert and existing text column to translatable. I find that when i add the column name to the the protected translatable array i am no longer able to access it as i did before ($model->key)
I assume that this is because its looked for a translation but can't find one. Is there a way for me to return to contents of the column? I want to retrieve the text and and replace it with a json
when I log $this i can see my object and the correct key: value pairs. Any attempt to access it or convert it to array causes the value to disappear completely
$array = json_decode(json_encode($this), true);
$object = json_decode(json_encode($this), false);
error_log('$this '.print_r($this,true)); // includes the key 'myKey' with correct value
error_log('$array '.print_r($array['mykey'],true)); // empty
error_log('$object '.print_r($object->mykey,true)); // empty
You can use this method if you want to get all translated values of a particular column as an array.
public function update(ModelName $modelItem)
{
return $modelItem->getTranslations('column_name');
}
//result
[
'en' => 'test',
'tr' => 'deneme',
]
Resource:
https://github.com/spatie/laravel-translatable#getting-all-translations-in-one-go
if you want to get the content that still not store as json translation, you can use this eloquent method.
$model->getRawOriginal('your translation's column name');
it will get your column value.

How to get only pure value from MySQL

I need value from MySQL send into PLC via OPC UA (in NODE-RED). Everything works ok, but I don't know how to get pure value without descriptions of array etc.
I use this code:
SELECT `user_info` FROM `users` WHERE `user_name` LIKE 'Lukas'
The answer is:
array[1]
0: object
user_info: "6"
If I send it to PLC as STRING the value in PLC is:
[object Object]
Can I edit the code somehow? I need answer only:
6
Thank you
The answer is array[1] 0: object user_info: "6"
I assume you've copied that out of the Debug window which shows you the exact structure of the payload you've received.
That is saying, the payload is an array with a single element. That element is an object with a user_info property of value 6.
In other words:
[
{
"user_info": "6"
}
]
In which case, to access the value you would use:
msg.payload[0].user_info
For example, a Function node to pull that value out and put it into the payload would be:
msg.payload = msg.payload[0].user_info;
return msg;
Or you could use a Change node to set the value of msg.payload to the value of msg.payload[0].user_info.

How to find if a property name exists in json response using Groovy script

I am trying to use Groovy script for my Json response in soapui and finding if the property exists in my response. I used If statement as below. For what ever property name i use to check it returns only true statement even though if the property not exists. I am not sure whats wrong I am doing here.
import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
def i = 0
responseContent = testRunner.testCase.getTestStepByName("DAY").getPropertyValue("response")
slurperresponse = new JsonSlurper().parseText(responseContent)
if(slurperresponse.day_details.activities.to_locans) {
println "************************"
res = "Crew_base found"
} else {
res = "Crew_base not found"
}
This is caused by a few things coming together:
Groovy returns a null for unknown keys
Groovy lets you use xpath type variable lookup, including if that goes via a nested list
Groovy truthy on a list is based on the list size - even if the list only contains null, if its not empty, then it evaluates to true.
Your comment above reveals the problem:
For valid property name
Fri Apr 22 16:01:19 EDT 2016:INFO:<java.util.ArrayList#260080 elementData=[[NYP, NYP]] size=1 modCount=1>
For invalid property name
Fri Apr 22 16:01:35 EDT 2016:INFO:<java.util.ArrayList#3e0 elementData=[[null, null]] size=1 modCount=1>
You see in both cases the result is a list (of lists) of two items - so always evaluates to true.
As a map, from your final comment where you print the dump of that variable, it looks like this:
[
day_details: [
[
fra_status:'', block_training_day:0, holiday_name:'', activities:[
[ from_location:'WAS', craft:'Conductor', departure_datetime:'2016-04-26T13:02:00-04:00', end_datetime:'2016-04-26T16:30:00-04:00', crew_base:'NYP', ends_next_day:false, description:'Unit', train_number:172, to_location:'NYP', arrival_datetime:'2016-04-26T16:30:00-04:00', zone:'Zone 2', start_datetime:'2016-04-26T12:52:00-04:00' ],
[ from_location:'NYP', craft:'Engineer', to_location:'WAS', zone:'Zone 2', start_datetime:'2016-04-26T17:55:00-04:00' ]
]
]
]
]
Reading that, you will see that day_details and activities are both nested lists (hence the two lists in the response - so groovy navigates to each of the maps inside activities and looks for the key to_locans - not finding the key, it returns null, and puts those two nulls into a list.
Changing the if check to the following will work as you originally intended (that is with the assumption that you only want to ever consider the first element in each of those lists):
if (slurperresponse.day_details[0].activities[0].to_locans){

JSON - look up values in array

With the following json
{
"Count":0,
"Message":{
"AppId":0
},
"Data":"[{\"application_name\": \"Grand Central\",\"feature_name\": \"1 Click Fix\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Details\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Summary\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"}]"
}
how do I go through the Data array, in the most succinct coding manner possible, to see if any feature_name matches a given string?
Since your JSON contains nested, quoted JSON, you will need nested deserializations using LINQ to JSON to parse your Data array. Having done so, you can use use SelectTokens to query with a JSONPath query to find nested properties named feature_name, then check their value:
var testString = "Account Summary";
var found = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString()).SelectTokens("..feature_name").Any(t => (string)t == testString);
Debug.Assert(found == true); // No assert.
Update
If you want the all JObject with a "feature_name" property matching a given value, you can do:
var foundItems = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString())
.SelectTokens("..feature_name")
.Where(t => (string)t == testString)
.Select(t => t.Ancestors().OfType<JObject>().First()) // Get the immediate parent JObject of the matching value
.ToList();

Data column(s) for axis #0 cannot be of type string error in google chart

I tried to populate google chart datatable in server side using PHP.I got JSON file properply, but the Chart not display in client Application. I got error-Data column(s) for axis #0 cannot be of type string . My coding is below here.
After fetching data from database,
$colarray=array(array("id"=>"","label"=>"userid","pattern"=>"","type"=>"number"),array("id"=>"","label"=>"name","pattern"=>"","type"=>"string"));
$final=array();
for($i=0;$i<$rows;$i++)
{
$id[$i]=pg_fetch_result($res1,$i,'id');
$name[$i]=pg_fetch_result($res1,$i,'name');
$prefinal[$i]=array("c"=>array(array("v"=>$name[$i]),array("v"=>$name[$i])));
array_push($final,$prefinal[$i]);
}
$table['cols']=$colarray;
$table['rows']=$final;
echo json_encode($table);
My Output Json:
{
"cols":[
{"id":"","label":"userid","pattern":"","type":"number"},
{"id":"","label":"name","pattern":"","type":"string"}
],
"rows":[
{"c":[{"v":"101"},{"v":"Aircel"}]},
{"c":[{"v":"102"},{"v":"Srini"}]},
{"c":[{"v":"103"},{"v":"Tamil"}]},
{"c":[{"v":"104"},{"v":"Thiyagu"}]},
{"c":[{"v":"105"},{"v":"Vasan"}]},
{"c":[{"v":"107"},{"v":"Senthil"}]},
{"c":[{"v":"108"},{"v":"Sri"}]},
{"c":[{"v":"109"},{"v":"Docomo"}]},
{"c":[{"v":"106"},{"v":"Innodea"}]}
]
}
How to solve this issue?
To extend on #sajal's accurate answer: Change the last line of your code from:
echo json_encode($table);
to:
echo json_encode($table, JSON_NUMERIC_CHECK);
This will tell json_encode to recognize numbers and abstain from wrapping them in quotes (Available since PHP 5.3.3.).
http://php.net/manual/en/json.constants.php#constant.json-numeric-check
You specify type of userid as number... but pass string.. thats causing the problem.
I just wasted 30 mins with the opposite problem ...
Your output json should look like :-
{
"cols":[
{"id":"","label":"userid","pattern":"","type":"number"},
{"id":"","label":"name","pattern":"","type":"string"}
],
"rows":[
{"c":[{"v":101},{"v":"Aircel"}]},
{"c":[{"v":102},{"v":"Srini"}]},
{"c":[{"v":103},{"v":"Tamil"}]},
{"c":[{"v":104},{"v":"Thiyagu"}]},
{"c":[{"v":105},{"v":"Vasan"}]},
{"c":[{"v":107},{"v":"Senthil"}]},
{"c":[{"v":108},{"v":"Sri"}]},
{"c":[{"v":109},{"v":"Docomo"}]},
{"c":[{"v":106},{"v":"Innodea"}]}
]
}
On a BarChart, one of the columns (the second one) has to be a number. That can cause this error message.
In your drawChart() function, you are probably using google.visualization.arrayToDataTable, and this does not allow any nulls. Please use addColumn function explicitly
If the Data format should be like:
data: [
["string", "string"], //first Column
["string1", number],
["string2", number],
["string3", number],
]
then you can overcome this error.
when you are passing your data from controller you need to do like so: just take an example I have controller and I am sending data through it via group by.
controller:
\DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query
$Rspatients = DB::table('reports')
->select(
DB::raw("day(created_at) as day"),
DB::raw("Count(*) as total_patients"))
->orderBy("created_at")
->groupBy(DB::raw("day(created_at)"))
->get();
$result_patients[] = ['day','Patients'];
foreach ($Rspatients as $key => $value) {
$result_patients[++$key] = [$value->day,$value->total_patients];
}
return view('Dashboard.index')
->with('result_patients',json_encode($result_patients,JSON_NUMERIC_CHECK));
if there is no JSON_NUMERIC_CHECK, so the data will be array of strings while if there is json check the data will be converted to array of numbers.
before JSON check data:
4: (2) ["24", "413"]
5: (2) ["25", "398"]
After JSON Check data:
4: (2) [24, 413]
5: (2) [25, 398]