How to check if JSON response fields are alphabetically sorted? - json

How to validate the JSON Response fields? After validating the fields I need to check whether the fields are alphabetically sorted or not. How would I do it ?

The JSON object is unordered set of name/value pairs. There is no guarangee of ordering at all. You need to take json object keys list and sort them. After sorting access to object fields by sorted keys list.
If you mean how to check list (array) of values. You need to implement simple loop through array and check that each element must be less than next element in sorting comparision criteria.
For js language checking array for alpha ordering may be done like this:
var array = ["Apple", "Application", "AppName", "Happy"];
var isSortedAlpha = array.reduce(function(res, current, index, arr) {
return res && arr[index&&index-1] <= current
}, true);

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.

Why does encoding an array into json format result in an json object?

This is strange, I've used json encoding arrays and the output is something like [{" etc, but in another code this time the output is "{"1":{".. causing multiple errors. I don't understand what is going on.
this is the part of the code:
$json_arr = json_decode($json_str, true);
$fecha = date("Y-m-d H:i:s");
foreach (array_column($json_arr, 'f') AS $k => $fecha) {
if($fecha < $ahora){
unset($json_arr[$k]);
}
}
$json_str = json_encode($json_arr,true);//this will be inserted in the DB table
but the $json_str is in the form of "{"1":{".. but I need in the form of [{".
Here some of the images when debugging:
in orange, the json_str is readed from the BD table
after decoding, you see the json_arr is an array of three elements
after deleting some row, you see json_arr is still an array
after encoding the json_arr, I get the "{"1":{" format, in other cases of encoding arrays I had the [{" format, which is what I need.
You are starting with an array of 3 arrays, with the indices of 0, 1, and 2.
Then you are deleting the first one. If you compare your 2nd and 3rd screenshots, specifically the popup portion, you'll see that what you have lost is index 0. Your array now starts with index 1.
But in JavaScript, an array can't start with index 1. It has to start with index 0, so PHP is encoding it as an object, instead of an array.
If you use the PHP function array_values() it will re-index your array and you should be good to go.

What's the correct JsonPath expression to search a JSON root object using Newtonsoft.Json.NET?

Most examples deal with the book store example from Stefan Gössner, however I'm struggling to define the correct JsonPath expression for a simple object (no array):
{ "Id": 1, "Name": "Test" }
To check if this json contains Id = 1.
I tried the following expression: $..?[(#.Id == 1]), but this does find any matches using Json.NET?
Also tried Manatee.Json for parsing, and there it seems the jsonpath expression could be like $[?($.Id == 1)] ?
The path that you posted is not valid. I think you meant $..[?(#.Id == 1)] (some characters were out of order). My answer assumes this.
The JSON Path that you're using indicates that the item you're looking for should be in an array.
$ start
.. recursive search (1)
[ array item specification
?( item-based query
#.Id == 1 where the item is an object with an "Id" with value == 1 at the root
) end item-based query
] end array item specification
(1) the conditions following this could match a value no matter how deep in the hierarchy it exists
You want to just navigate the object directly. Using $.Id will return 1, which you can validate in your application.
All of that said...
It sounds to me like you want to validate that the Id property is 1 rather than to search an array for an object where the Id property is 1. To do this, you want JSON Schema, not JSON Path.
JSON Path is a query language for searching for values which meet certain conditions (e.g. an object where Id == 1.
JSON Schema is for validating that the JSON meet certain requirements (your data's in the right shape). A JSON Schema to validate that your object has a value of 1 could be something like
{
"properties": {
"Id": {"const":1}
}
}
Granted this isn't very useful because it'll only validate that the Id property is 1, which ideally should only be true for one object.

Laravel - Group By & Key By together

Assuming I have the following MySQL tables to represent pricebooks, items and the relationship between them:
item - item_id|name|...etc
pricebook - pricebook_id|name|...etc
and the following pivot table
pricebook_item - pricebook_id|item_id|price|...etc
I have the correlating Eloquent models: Pricebook, Item and a repository named PricebookData to retrieve the necessary information.
Within the PricebookData repository, I need to get the pricebook data grouped by pricebook id and then keyed by item_id for easy access on client side.
If I do:
Pricebook::all()->groupBy('pricebook_id');
I get the information grouped by the pricebook_id but inside each pricebook the keys are simple numeric index (it arrives as js array) and not the actual product_id. So when returning to client side Javascript, the result arrives as the following:
pricebookData: {1: [{}, {}, {}...], 2: [{}, {}, {}...]}
The problem with the prices arriving as array, is that I can not access it easily without iterating the array. Ideally I would be able to receive it as:
pricebookData: {1: {1001:{}, 1002: {}, 1003: {}}, 2: {1001:{}, 1002: {}, 1003: {}}}
//where 1001, 1002, 1003 are actual item ids
//with this result format, I could simply do var price = pricebookData[1][1001]
I've also tried the following but without success:
Pricebook::all()->keyBy('item_id')->groupBy('pricebook_id');
The equivalent of what I am trying to avoid is:
$prices = Pricebook::all();
$priceData = [];
foreach ($prices as $price)
{
if (!isset($priceData[$price->pricebook_id]))
{
$priceData[$price->pricebook_id] = [];
}
$priceData[$price->pricebook_id][$price->item_id] = $price;
}
return $priceData;
I am trying to find a pure elegant Eloquent/Query Builder solution.
I think what you want is
Pricebook::all()
->groupBy('pricebook_id')
->map(function ($pb) { return $pb->keyBy('item_id'); });
You first group by Pricebook, then each Pricebook subset is keyed by item_id. You were on the right track with
Pricebook::all()->keyBy('item_id')->groupBy('pricebook_id');
unfortunately, as it is implemented, the groupBy resets previous keys.
Update:
Pricebook::all()->keyBy('item_id')->groupBy('pricebook_id', true);
(groupBy second parameter $preserveKeys)

How should I search through this json structure?

I'm working with PHP, I have a json structure which looks like that :
{
"events": [
{
"timestamp": 1468774519,
"id": 75964,
},
{
"timestamp": 1468771410,
"id": 24891,
},
// etc
I need to fetch 5 events in a row, but starting from one specific id, so my first idea is to loop every event from the beginning and check if the id is the offset i'm looking for, and then when i get it i can loop the next 5 events.
But is there a better way to do so ? It could possibly loop through hundreds of events so maybe there's a better way to get there ? thanks
Since the ids aren't in numeric order, you can't use a binary search, so you need to use a sequential search. Here's an example in JavaScript. Also note this code assumes the id is present and there are at least four more events after it in the array.
var index = 0;
var id = 12345; // for example
var json = {...}; // whatever that object was
while(json.events[index].id!=id) {
index++;
}
// found the one, do something with the next five
for(var i=0; i<5; i++) {
var event = json.events[index+i];
// do something
}
In my opinion, you can only take one loop over the events with a filter event.id >= theId,and then check if the filtered array contains theId. if you get it, you can sort this smaller array and take the 5 events.
First I would make a key:value hash object (a lookup object), where the key would be the id from your structure, and the value would be the reference to the event. As a result, you iterate over the structure only once and then get all the events from the lookup structure, by just accessing them by their keys.
You could sort it as well(ideally, you could get it already sorted by id from your source of data) and then use a binary search algorithm.