How do I access certain elements with jmespath using slicing? - json

I have the following JSON
{
"items": [
{
"configurationStatus": "SYNCED",
"conflictDetectionState": "IN_SYNC",
"connectivityState": "ONLINE",
I can access individual elements inside with items[*].isModel, but, I cannot figure out how to access the first 3 elements. I tried something like this items[*].[0:2], but it didn't work. I am curious how to access the first 3 elements using slicing.

You would possibly face some issue trying to achieve this because, as pointed in the JMESPath documentation, object are:
object (an unordered collection of key value pairs)
Source: https://jmespath.org/specification.html, emphasis, mine
So you might end up with different keys based on the implementation and have really random results.
Now the issue with your approach is that slices can only act on arrays.
A slice expression allows you to select a contiguous subset of an array.
Source: https://jmespath.org/specification.html#slices, emphasis, mine
What you could do then, in order to have an array out of a hash is to use the values function, but mind that you'll lose the key/value association in the process.
Then, given you have an array, you can now apply the slicing technique.
So with the query:
items[].values(#)[0:3]
On the JSON:
{
"items": [
{
"configurationStatus": "SYNCED",
"conflictDetectionState": "IN_SYNC",
"connectivityState": "ONLINE",
"foo": "bar",
"baz": "qux"
},
{
"configurationStatus": "SYNCED′",
"conflictDetectionState": "IN_SYNC′",
"connectivityState": "ONLINE′",
"foo": "bar′",
"baz": "qux′"
}
]
}
This would give:
[
[
"SYNCED",
"IN_SYNC",
"ONLINE"
],
[
"SYNCED′",
"IN_SYNC′",
"ONLINE′"
]
]

Related

JSONPath to get multiple values from nested json

I have a nested JSON in a field that contains multiple important keys that I would like to retrieve as an array:
{
"tasks": [
{
"id": "task_1",
"name": "task_1_name",
"assignees": [
{
"id": "assignee_1",
"name": "assignee_1_name"
}
]
},
{
"id": "task_2",
"name": "task_2_name",
"assignees": [
{
"id": "assignee_2",
"name": "assignee_2_name"
},
{
"id": "assignee_3",
"name": "assignee_3_name"
}
]}]}
All the queries that I've tried so far fx ( $.tasks.*.assignees..id) and many others have returned
[
"assignee_1",
"assignee_2",
"assignee_3"
]
But what I need is:
[
["assignee_1"],
["assignee_2", "assignee_3"]
]
Is it possible to do with JSONPath or any script inside of it, without involving 3rd party tools?
The problem you're facing is that tasks and assignees are arrays. You need to use [*] instead of .* to get the items in the array. So your path should look like
$.tasks[*].assignees[*].id
You can try it at https://json-everything.net/json-path.
NOTE The output from my site will give you both the value and its location within the original document.
Edit
(I didn't read the whole thing :) )
You're not going to be able to get
[
["assignee_1"],
["assignee_2", "assignee_3"]
]
because, as #Tomalak mentioned, JSON Path is a query language. It's going to remove all structure and return only values.

Oder of my json request is getting sorted in alphabetical order when i am getting data from data file.i dnt want my json request to get sorted

{
"ID":0,
"OrganizationId":"",
"OrganizationName":"",
"Name":"",
"IsActive":"True",
"Type":2,
"AppliesTo":1,
"TagHOD":"",
"DisplayAsPrimary":"false",
"Values":[
]
}
Above is my json request which I have stored in a data file
Below is my json request body which I am getting after sending a parameter into it. It is sorted into alphabetical order which I don't want. I want the same order as above eg ID Should be first then OrganizationId
{
"AppliesTo": 1,
"DisplayAsPrimary": "false",
"ID": 0,
"IsActive": "True",
"Name": "TAG1205510333275",
"OrganizationId": 2404,
"OrganizationName": "",
"TagHOD": "",
"Type": 2,
"Values": [
{
"HODEmail": "tagsapiautomationae#mailinator.com",
"Id": 1,
"IsDeleted": false,
"Text": "Level20"
}
]
}
The JSON specification states: "An object is an unordered set of name/value pairs."
When working with JSON (and objects in most languages), the properties in objects are inherently unordered. You can't rely on different systems giving you the properties in the same order you supply them. In fact, you can't even rely on a single system giving you the properties in the same order all the time within a given execution of the code, even though many systems do behave that way.
If you want to preserve ordering, you either need to use an array to store the data, or you can use an array of object property names that stores the keys in the order you want, so you can use that array to reference them in the desired order later.
EG:
keyorder = ["ID",
"OrganizationId",
"OrganizationName",
"Name",
"IsActive",
"Type",
"AppliesTo",
"TagHOD",
"DisplayAsPrimary",
"Values"
]
You can then loop over this array when accessing elements in your object, so you are always accessing them in your defined order.
In python, with an object named "data" this would look like:
for key in keyorder:
print data.get(key)

JSON Notation - Lists with Single Member

Let's say I have a JSON structure that contains the following:
{
"ROWS": [{
"name": "Greg",
"age": "24",
},
{
"name": "Tom",
"age": "53",
}]
}
The value for the key "ROWS" is a list of dictionaries, right?
Okay, well what if I only have one entry? Is it still appropriate to use list notation, even if that list has a single element?
{
"ROWS": [{
"name": "Greg",
"age": "24",
}]
}
Would there be any reason I could NOT do this?
There is no technical reason why you could not use a list. Your array could be empty and that's perfectly acceptable and valid technically.
For your ROWS property I think the most important thing to consider is how many rows you could possibly have. You want to incorporate the computer engineering principle of generality to make sure you don't paint yourself into a corner by making ROWS an object. If you can expect to ever have more then one object as a row, even if currently there is only one, then it's absolutely appropriate to use an array.
For example let's assume you expect to get a unique record such as a login system. Then it wouldn't make sense to use an array , in this case you should use an object instead
{
"LOGIN_ROW": {
"name": "Greg",
"age": "24",
}
}
Again I said should because it's up to you to format your json object graph. But of course if you have a scenario where you have a list of employees then it would make sense to use an array:
{
"LIST_OF_ROWS": [{
"name": "Greg",
"age": "24",
}]
}
This is perfectly fine because you have one employee at this time but you wish to expand your company so you would expect to get more employees.

Binding embedded Json in ember

How does bind values of embedded JSON data to input elements in EmberJS as I cannot seem to find a straight forward way to get that done.
update
It doesn't seem to work for a JSON object with this structure
{
"users": [
{
"_id": "534550428047526419000002",
"Name": "admin",
"Code": "admin",
"Age": 12,
"Sex": "Male",
"Ethnicity": "admin",
"EventTime": "",
"Accident": [
{
"value": true,
"risk": "Medium"
}
]
}
]
}
In the template you use the property name
{{foo}}
{{input value=foo}}
Example
http://emberjs.jsbin.com/wufegaca/1/edit
nested properties are handled the same way they are in most languages with the dot operator
{{foo.bar}}
{{input value=foo.bar}}
Example
http://emberjs.jsbin.com/wufegaca/2/edit
Using an array you need to iterate over the array. If you didn't how would Ember know which item you were referring to? Additionally upper case property names are problematic in handlebars, since it usually denotes a global namespace, so be wary if things don't appear to be working.
Example
http://emberjs.jsbin.com/wufegaca/3/edit

How should a JSON response be formatted?

I have a REST service that returns a list of objects. Each object contains objectcode and objectname.
This is my first time building a REST service, so I'm not sure how to format the response.
Should it be:
{
"objects": {
"count": 2,
"object": [
{
"objectcode": "1",
"objectname": "foo"
},
{
"objectcode": "2",
"objectname": "bar"
},
...more objects
]
}
}
OR
[
{
"objectcode": "1",
"objectname": "foo"
},
{
"objectcode": "2",
"objectname": "bar"
},
...more objects
]
I realize this might be a little subjective, but which would be easier to consume? I would also need to support XML formatted response later.
They are the same to consume, as a library handles both just fine. The first one has an advantage over the second though: You will be able to expand the response to include other information additional to the objects (for example, categories) without breaking existing code.
Something like
{
"objects": {
"count": 2,
"object": [
{
"objectcode": "1",
"objectname": "foo"
},
{
"objectcode": "2",
"objectname": "bar"
},
...more objects
]
}
"categories": {
"count": 2,
"category" : [
{ "name": "some category"}
]
}
}
Additionally, the json shouldn't be formatted in any way, so remove whitespace, linebreaks etc. Also, the count isn't really necessary, as it will be saved while parsing the objects themselves.
I often see the first one. Sometimes it's easier to manipulate data to have meta-data. For exemple google API use first one : http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
It's not only the question of personal preference; it's also the question fo your requirements. For example, if I was in the same situation and I did need object count on client side then I'd go with first approach otherwise I will choose the second one.
Also please note that "classic" REST server mostly will work a bit different way. If some REST function is to return a list of objects then it should return only a list of URLs to those objects. The URLs should be pointing to details endpoints - so by querying each endpoint you may get details on specific single object.
As a client I would prefer the second format. If the first format only includes the number of "objects", this is redundant information.