In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)
Related
I'm trying to dynamically add an object inside every object which is present in my json array. But I'm unable to do so. My object is getting appended at the end of json which is not what I want.
jsonArray:any=[
{
"id": 1000,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "some comment",
"postId": 1
},
{
"id": 3,
"body": "some comment",
"postId": 1
}
]
selectFLag:any={"selected":"true"}
temArray:any;
learnJSONPArse()
{
for (var i = 0; this.jsonArray.length > i; i++)
{
Alert(this.jsonArray.length)
}
}
this.jsonArray.push(this.selectFLag)
-----expected output is
[
{
"id": 1000,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 2,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 3,
"body": "some comment",
"postId": 1,
"selected":"true"
}
]
You're question is a little unclear, but it sounds like you want to map each item in your array to a new item. The new item is the same as the old one, but assigned an additional property.
If so, something like this could work for you:
const objToAppend = { selected: true };
jsonArray.map(item => Object.assign(item, objToAppend));
Refs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
AngularJS Service:
Get json sub-record field for import into current open array record.
I have one json file with "services" in it (id, name) services.json,
I need to forEach through them, but as I am in each service I need to open sub-record(welding.json) and grab a field(title) and add it to the current record.
NOTE: My project is a CLI type.
services.json
[
{
"id": 1,
"name": "welding"
},
{
"id": 2,
"name": "carpentry"
},
{
"id": 3,
"name": "mechanic"
}
]
= Sub-Records =
welding.json
{
"category": "labor",
"title": "Arc Welding",
"description": "",
"experience": "20+ Years",
"details": ""
}
Expectation:
{
"id": 1,
"name": "welding",
"title": "Arc Welding"
}
Try this
angular.forEach($scope.services, function (value, key) {
if(value.name == 'welding'){
$http.get('welding.json').then(function (response) {
$scope.welding = response;
})
$scope.services.title=$scope.welding.title;
}});
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()
{
"data": [
{
"_id": 555,
"username": "jackson",
"status": "i am coding",
"comments": [
{
"user": "bob",
"comment": "bob me "
},
{
"user": "daniel",
"comment": "bob the builder"
},
{
"user": "jesus",
"comment": "bob the builder"
},
{
"user": "hunter",
"comment": "bob the builder"
},
{
"user": "jeo",
"comment": "bob the builder"
},
{
"user": "jill",
"comment": "bob the builder"
}
]
}
]
}
so i want to get the result with _id :555 and user:bob i tried with below code but i cant make it work it returns empty array
app.get('/all',function(req , res){
db.facebook.find({_id:555},{comments:[{user:"bob"}]},function(err,docs){res.send(docs,{data:docs});});
} );
i want the result to be like this listed below with the comment with user:bob
{
"_id": 555,
"username": "jackson",
"status": "i am coding",
"comments": [
{
"user": "bob",
"comment": "bob me "
}
]
}
Only aggregate or mapReduce could exclude items from subarray in output. Shortest is to use $redact:
db.facebook.aggregate({
$redact:{
$cond:{
if:{$and:[{$not:"$username"},{$ne:["$user","bob"]}]},
then: "$$PRUNE",
else: "$$DESCEND"
}
}
})
Explanation:
$reduct would be applied to each subdocument starting from whole document. For each subdocument $reduct would either prune it or descend. We want to keep top level document, that is why we have {$not:"$username"} condition. It prevents top level document from pruning. On next level we have comments array. $prune would apply condition to each item of comments array. First condition {$not:"$username"} is true for all comments, and second condition {$ne:["$user","bob"]} is true for all subdocuments where user!="bob", so such documents would be pruned.
Update: in node.js with mongodb native driver
db.facebook.aggregate([{
$redact:{
$cond:{
if:{$and:[{$not:"$username"},{$ne:["$user","bob"]}]},
then: "$$PRUNE",
else: "$$DESCEND"
}
}
}], function(err,docs){})
One more thing: $prune is new operator and available only in MongoDB 2.6
I have three classes representing different sections in my models: SectionA, SectionB, SectionC.
Each of these sections have associated a set of items (class Item in my model).
I would like to get a json similar to this:
{
"sectionA": [
{
"id": 1,
"picture": "car_pic1",
"category": "cat1"
},
{
"id": 3,
"picture": "car_pic1",
"category": "cat2"
},
{
"id": 5,
"picture": "car_pic1",
"category": "cat3"
}
],
"sectionB": [
{
"id": 2,
"picture": "car_pic1",
"category": "cat8"
},
{
"id": 4,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 7,
"picture": "car_pic1",
"category": "cat10"
},
],
"sectionC": [
{
"id": 9,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 10,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 11,
"picture": "car_pic1",
"category": "cat10"
},
]
}
This json displays any three items associated to each section.
I would like to know how can I implement this using rest-framework. Basically I need to perform a query retrieving the three items for each section (since this json is not associated to a model object) and serialize all this into the json. I'm not sure where or how to perform these queries and I didn't have any success so far.
Finally I did it slightly different. My view just creates a dictionary with each section and its associated items:
class SectionList(APIView):
"""
List three objects for each section.
"""
def generate_data(self):
#query to get the items of each section
list_items = []
list_items.append({"section" : "sectionA", "items" : secA_items})
list_items.append({"section" : "sectionB", "items" : secB_items})
list_items.append({"section" : "sectionC", "items" : secC_items})
return list_items;
def get(self, request, format=None):
section_list = self.generate_data()
serializer = SectionSerializer(section_list)
return Response(serializer.data)
And this is the serializer I used:
class SectionSerializer(serializers.Serializer):
section = serializers.CharField(max_length=200)
items = ItemSerializer(many=True)