Get array of JSON keys in react native - json

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]).

Related

How to get the the node object or array from JSON based on excel sheet data using groovy?

Lets say I have the following JSON :-
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
And, I am passing the value of author from excel sheet to check if that author is present or not. If that author is present inside JSON, then that that particular array node only and remove other from the JSON.
For Example:- I am passing "author" value as "Herbert Schildt" from excel sheet. Now this value is present inside JSON, So, I need this particular array node to be printed and rest all should be removed. Like this:-
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
}
Can it be done using groovy? I have tried with HashMap but couldn't get through.
It's quite easy using groovy:
def text = '''{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
'''
def result = groovy.json.JsonOutput.toJson(
[book: new groovy.json.JsonSlurper().parseText(text).book.findAll{it.author == "Herbert Schildt"}]
)
println result
You may try this ways json search
var json = '{"book":[{"id":"01","language":"Java","edition":"third","author":"Herbert Schildt"},{"id":"07","language":"C++","edition":"second","author":"E.Balagurusamy"}]}';
var parsed = JSON.parse(json);
var result = {};
result.book = [];
var author = "Herbert Schildt";
parsed.book.map((i, j) => {
if(i.author == author) {
result.book.push(i);
}
});
console.log(result)

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})

Select2 json data not working

I am trying to hook select2 when an element has class "select2picker" i am also customising if the source of the dropdown list is an array. My code below
$('.select2picker').each(function() {
var settings = {};
if ($(this).attr('data-json')) {
var jsonValue = JSON.parse($(this).attr('data-json')).val());
settings = {
placeholder: $(this).attr('data-placeholder'),
minimumInputLength: $(this).attr('data-minimumInputLength'),
allowClear: true,
data: jsonValue
}
}
$(this).select2(settings);
});
but the result is horrible it fails to hook all the select2 dropdownlist
but when I comment out the data property, the output shows perfect (but the data binding goes missing)
My array looks like the following
[ { "id": "2015-0152", "text": "2015-0152" }, { "id": "2015-0153", "text": "2015-0153" }, { "id": "2016-0001", "text": "2016-0001" }, { "id": "2016-0002", "text": "2016-0002" }, { "id": "2016-0003", "text": "2016-0003" }, { "id": "2016-0004", "text": "2016-0004" }, { "id": "2016-0005", "text": "2016-0005" }, { "id": "2016-0006", "text": "2016-0006" }, { "id": "2016-0007", "text": "2016-0007" }, { ... }, { "id": "2015-0100", "text": "2015-0100" }, { "id": "2015-0101", "text": "2015-0101" }, { "id": "2015-0080", "text": "2015-0080" }, { "id": "2015-0081", "text": "2015-0081" }, { "id": "2015-0090", "text": "2015-0090" }, { "id": "2015-0102", "text": "2015-0102" }, { "id": "2015-0112", "text": "2015-0112" }, { "id": "2015-0128", "text": "2015-0128" }, { "id": "2015-0136", "text": "2015-0136" } ]
I am really confused about what is going wrong. Any idea?
Select2 version: 3.4.8
This line gives an error: var jsonValue = JSON.parse($(this).attr('data-json')).val());
Should be: var jsonValue = JSON.parse($(this).attr('data-json'));.
Also this line in your question:
i am also customising if the source of the dropdown list is an array
Indicates to me that it might also not be an array. In that cause you should check if it is an array before you pass the data to select2.
EDITED: Another thing that came to my mind was the following.
If you're using data properties for the placeholder I don't think you need to pass the values of those properties to select2 a second time like you do here
placeholder: $(this).attr('data-placeholder'),
minimumInputLength: $(this).attr('data-minimumInputLength'),
Might be that you need to pick one of the two (either pass it along in your settings, or use an attribute). As select2 looks at the data attributes to get a value.
I checked if the above was correct turns out it isn't. It works fine in this fiddle: https://jsfiddle.net/wL7oxbpv/
I think there is something wrong with your array data. Please check that.

How to input nested json to jquery tokeninput?

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.

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()