How to input nested json to jquery tokeninput? - json

I use jquery tokeninput.
A flatted json is no problem to be searched. but howto input nested object.
my code:
var flat_obj = [{id: 7, name: "Ruby"}, {id: 11, name: "Python"}];
var nested_obj = [{ "name": "main", "id": "2", "Parent": "0", "children": [{ "name": "submain", "id": "3", "Parent": "2"}] }];
$("#search-input-local").tokenInput(nested_obj, { });

TokenInput doesn't handle nested JSON, you will need to format the JSON correctly before you pass it to the plugin.
There are a number of libraries to flatten JSON, or take a look at this question here.

Related

Gpath for JSON with nested findAll

I have the following response payload
[{
"id": 1,
"catname": "Cat01",
"items": [{
"Name": "Item01",
"id": 2
}, {
"Name": "Item02",
"id": 3
}]
},
{
"id": 4,
"catname": "Cat02",
"items": [{
"Name": "Item03",
"id": 5
}, {
"Name": "Item04",
"id": 6
}]
},
{
"id": 7,
"catname": "Cat03",
"items": [{
"Name": "Item05",
"id": 8
}]
}
]
I want to retrieve a list of all the items.ids (but not the ids of their parents), So this: [2, 3, 5, 6, 8].
I've tried this findAll{it}.items.findAll{it}.id but it doesn't work. Any help would be welcomed. Thanks!
You don't need to use findAll here to iterate, and you can make use of collectMany to automatically flatten the list
Assuming your parsed json is in a variable json, you can simply do:
json.items.collectMany { it.id }
Never mind, I found the answer :).
I needed to use flatten here
items.flatten().id
did the trick.
I got the answer from here: How to search in anonymous and nested array using find or findAll in groovy's closures using REST-Assured library?

Get array of JSON keys in react native

I have a JSON data in the format
[{
"Heading1": [{
"questionID": "q1",
"questionTitle": "Question 1",
"question": "This is question1",
"status": 0,
"files": [],
"uploadType": "none"
}, {
"questionID": "q2",
"questionTitle": "Question 2",
"question": "This is question2",
"status": 0,
"files": [],
"uploadType": "none"
}]
}, {
"Heading2": [{
"questionID": "q3",
"questionTitle": "Question 11",
"question": "This is a question11",
"status": 0,
"files": [],
"uploadType": "none"
}]
}, {
"Heading3": [{
"questionID": "q4",
"questionTitle": "Question 1",
"question": "This is a question",
"status": 0,
"files": [],
"uploadType": "none"
}]
}]
I'm trying to get all the titles in a format like [{"Title":"Heading1"},{"Title":"Heading2"},{"Title":"Heading3"}]
How should I go about it?
First, if you really have JSON (e.g., your starting point is a string, such as from an ajax response), you parse it via JSON.parse to get an array of objects. Then you loop the array and get the only key from each of those top-level objects via Object.keys(x)[0] and map that to an array of objects in the form you want:
const json = '[{"Heading1":[{"questionID":"q1","questionTitle":"Question 1","question":"This is question1","status":0,"files":[],"uploadType":"none"},{"questionID":"q2","questionTitle":"Question 2","question":"This is question2","status":0,"files":[],"uploadType":"none"}]},{"Heading2":[{"questionID":"q3","questionTitle":"Question 11","question":"This is a question11","status":0,"files":[],"uploadType":"none"}]},{"Heading3":[{"questionID":"q4","questionTitle":"Question 1","question":"This is a question","status":0,"files":[],"uploadType":"none"}]}]';
const parsed = JSON.parse(json);
const result = parsed.map(entry => {
return {Title: Object.keys(entry)[0]};
});
console.log(result);
The map callback can be a concise arrow function, but I thought using the verbose form above would be clearer. The concise form would be:
const result = parsed.map(entry => ({Title: Object.keys(entry)[0]}));
Note that using Object.keys in this way is only reliable if the objects really have just one property, as in your question. If they have more than one property, the order the properties are listed in the array from Object.keys is not defined (even in ES2015+, where properties do have an order — Object.keys is not required to follow that order [although it does on every modern engine I've tested]).

Rails 4: Trying to use Ancestry with jstree

I am new to Rails and trying to populate a jstree in the browser with JSON from the Ancestry gem (see https://github.com/stefankroes/ancestry). JSON is the go-between. Where I am stuck is translating the JSON produced (from my Tree model) by Ancestry:
<%= #trees.arrange_serializable.to_json %>
That gives me nice JSON as follows (fragment only, apologies for the nonsense values):
[
{
"id": 2,
"name": "Milk",
"note": "No details available",
"created_at": "2014-09-20T13:22:03.262Z",
"updated_at": "2014-09-20T13:48:46.301Z",
"value": "3.06",
"ancestry": null,
"children": [
{
"id": 1,
"name": "Farms",
"note": "Some note here",
"created_at": "2014-09-20T13:05:22.186Z",
"updated_at": "2014-10-03T11:30:39.029Z",
"value": "432.0",
"ancestry": "2",
"children": [
{
"id": 8,
"name": "Zog",
"note": "Orc",
"created_at": "2014-09-27T22:11:20.874Z",
"updated_at": "2014-10-03T11:30:38.989Z",
"value": "11.0",
"ancestry": "2/1",
"children": [
{
"id": 14,
"name": "Planes",
"note": "",
"created_at": "2014-10-04T01:01:12.890Z",
"updated_at": "2014-10-04T04:51:20.873Z",
"value": "422.0",
"ancestry": "2/1/8",
"children": []
}
]
},
but the jstree plugin requires a particular format for the JSON as follows (from http://www.jstree.com/docs/json/):
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
While the source hierarchical structure is perfect, I need to replace the attribute "name" in the original with "text" in the output, plus a few other changes.
At the back of my mind I feel there should be something elegant (like XSLT for XML) to translate JSON#1 into JSON#2 but I can't find any examples that do this.

Json Slupper assert and extract

I'm using the next Json
{
"ID": 8,
"MenuItems": [
{
"ID": 38,
"Name": "Home",
"URL": "{\"PageLayout\":\"Home\",\"Icon\":\"home\"}",
"Culture": "en",
"Children": null
},
{
"ID": 534,
"Name": "GUIDE ",
"URL": "{''PageLayout'':''Page A'', ''Icon'':''A''}",
"MenuType": 1,
"PageID": 0,
"Culture": "en",
"Children": [
{
"ID": 6,
"Name": "Form A",
"URL": "[''Type'':''Form A'',''Icon'':''Form'',''ItemID'':\"358\"]",
"Culture": "he",
"RuleID": 0
},
{
"ID": 60,
"Name": "Drama",
"URL": "[''Type'':''Form B'',''Icon'':''Form'',''ItemID'':\"3759\"]",
"Culture": "en",
"RuleID": 0
}
]
}
]
}
i'm using Groovy script in soapUI and i need to:
Assert the exitance of node that has the name GUIDE
Extract a list of all Itemsid
You can parse the JSON content using JsonSlurper and then work with the results like so:
import groovy.json.JsonSlurper
// Assuming your JSON is stored in "jsonString"
def jsonContent = new JsonSlurper().parseText(jsonString)
// Assert node exists with name GUIDE
assert(jsonContent.MenuItems.Name.contains("GUIDE"))
// Get list of ItemIDs
def itemList = jsonContent.MenuItems.Children.URL.ItemID[0].toList()
// List the items
itemList.each {log.info it}
Note that the above will fail given your current example, because of a few issues. Firstly, Name contains "GUIDE " (trailing space) rather than "GUIDE" (so you will need to adapt accordingly). Secondly, it is invalid JSON; the URL nodes have various erroneous characters.
On a side note, if you first need to retrieve your JSON from the response associated with a previous TestStep (say one called "SendMessage") within the existing testCase, this can be done as follows:
def jsonString = context.testCase.getTestStepByName("SendMessage").testRequest.response.getContentAsString()

How to map json data coming from an REST-API to ember.js model?

I'm new to EmberJS and try to connect my EmberJS-frontend to an API via the RESTAdapter. I'm using ember-1.0.0-rc.6 and ember-data-latest (Version: v0.13-59-ge999edb).
From the API I get the following JSON code:
{
"page": 1,
"limit": 5,
"total": 4,
"results": [
{
"id": 1,
"title": "something3",
"description": "asd3"
},
{
"id": 2,
"title": "something3",
"description": "asd3"
},
{
"id": 3,
"title": "something2",
"description": "asd2"
},
{
"id": 4,
"title": "something",
"description": "asd"
}
]
}
My RESTAdapter looks like the following:
App.Store = DS.Store.extend({
revision: 13,
adapter: DS.RESTAdapter.extend({
url:"http://localhost/api/app_dev.php"
})
});
My model looks like this at the moment:
App.Modelname = DS.Model.extend({
title: DS.attr('string')
});
With this I get the following error in the browser console:
Assertion failed: Your server returned a hash with the key page but you have no mapping for it
MY question is how to connect the json output from the api to my ember model without changing the api on the server?
Thanks in advance for your support !
If your model is like this:
App.Modelname = DS.Model.extend({
title: DS.attr('string')
});
Then the RESTAdapter expects a JSON format like this:
{
"modelNames": [
{
"id": 1,
"title": "something3",
"description": "asd3"
},
{
"id": 2,
"title": "something3",
"description": "asd3"
},
{
"id": 3,
"title": "something2",
"description": "asd2"
},
{
"id": 4,
"title": "something",
"description": "asd"
}
]
}
You can of course tweak some of this behavior by configuring some aspects of the JSONSerializer and the RESTAdapter, IMO to have full control I would suggest to create your own adapter by overriding the vital functions like find, findAll etc. and go with plain $.ajax(...). Otherwise you would need to make your backend obey the JSON format ember-data expects.
Hope it helps, at least to take a decision.