Iterating through JSON object with Angular 2 ngFor - json

Before I write a service to get json, I just want to use some dummy json to test the front end. What's the correct way to iterate through json with ngFor? I tried the code below with a simple interface.
In the component.ts file (ngOnInit()):
var jsonSample = {
"name": "sample1",
"content": [
{
"id": "3",
"name": "Test",
"value": "45"
},
{
"id": "4",
"name": "Test2",
"value": "60",
}]
}
var items: Array<IContent> = jsonSample.content;
Then in the HTML:
<tr *ngFor='let content of items'>
<td>{{content.name | lowercase}}</td>
<td>{{content.id}}</td>
<td>{{content.value}}</td>
</tr>
Should I be trying to use JSON.parse instead?

Your *ngFor looks fine as far as json object traversal is concerned.
You do not need to do JSON.parse here as you have set an object directly.
In the case of receiving response from a service check here. You will be doing res.json() to parse and get json data from the Response object.

#torazaburo got it. I just had to change:
var items: Array<IContent> = jsonSample.content;
to
items: IContent[];
this.items = jsonSample.content;

Related

Why I can't access nested data from MongoDB collection like normal JSON file?

so I try to fetch data from my MongoDB collection using mongoose and typescript.
I can successfuly get fetched data but the problem I have is, that I can only access _id, season and avatar with syntax like {{response.season}} or {{response.avatar}}. Nested data inside avatar JSON object can be accessed only like it's dictionary {{response.avatar["transfer"]}} and I'm not sure why is that. I would like to access it like {{response.avatar.transfer}}, is it possible to do that ?
Fetching data from MongoDB using mongoose
export default async function run() {
// 4. Connect to MongoDB
await mongoose.connect(config.publicRuntimeConfig.MONGO_URI);
const results = await User.findOne({
'season': '123'
})
await mongoose.disconnect();
return results
}
Data I receive
{
"_id": "630fbca3d06e5e2f310ea540",
"season": 123,
"avatar": {
"from_team_id": 1,
"to_team_id": 2,
"transfer": "asdasd",
"type": "dasdasd",
"date": "asdasd",
"amount": "asdasd",
"player": {
"player_id": 12,
"country_id": 412,
"display_name": "asdasd",
"nationality": "asdasd",
"_id": "630fbca3d06e5e2f310ea542"
},
"_id": "630fbca3d06e5e2f310ea541"
},
"__v": 0
}
I want to access data like this if it's possible
<template v-for="transfer in transferData">
{{transfer.avatar.amount}}
</template>
What I can do now is
<template v-for="transfer in transferData">
{{transfer.avatar["amount"]}}
</template>
Is it possible to do that?
You can access all of the response objects properties by defining a type or interface and setting the response object as that type. I'd recommend defining a type for your avatar and player object and then one for the entire response that contains the avatar type you defined.
type response = {
"_id”:string;
avatar:Avatar
// The rest of your properties
}
type avatar = {
“from_team_id”:string;
player:Player;
// Rest of properties
}

parsing json response in react native

in react native my Json Response stores in state mydata as array.
console.log return the following
Array [
Object {
"cat": "NAMKIN",
"cat_id": 2,
"id": 4,
"item_name": "METHI MATHRI",
"photo": "exit4.png",
"price": 220,
},
]
So How can I access item_name and price in Text component
assign this to resp object
<Text>{resp[0].item_name]}</Text>
also do some check for potentially undefined resp
If you want just one item so you can access using bracket notation.
console.log(mydata[0].item_name, mydata[0].price);
And you want to render all objects of array so use the map function
mydata.map(item => console.log(item.item_name, item.));

get by id from local json http

I have fake users.json file and I can http.get to list the array of json.
Since I want to get the particular user by id and haven't stored the data in the database, instead just use the fake json data.
[
{
"id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
"name": "john",
"age": "25",
"country": "germany"
},
{
"id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
"name": "tom",
"age": "28",
"country": "canada"
}
]
I can do this stuff if the data is stored in the database, but not sure how to proceed with the fake json data.
Any help is appreciated.
Thanks
If you need the json as raw data, for just fake data, You can simply require it and use it as object..
const JsonObj = require('path/to/file.json')
console.log(JsonObj[0].id) // <-- cb55524d-1454-4b12-92a8-0437e8e6ede7
Plus, if you need more dynamic solution, there is a good JSON-server you can easily use for testing and so: check this git repo
var _ = require('underscore');
var dummyJson = [
{
"id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
"name": "john",
"age": "25",
"country": "germany"
},
{
"id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
"name": "tom",
"age": "28",
"country": "canada"
}
]
var requiredID = "cb55524d-1454-4b12-92a8-0437e8e6ede7";
var reuiredObject = _.find(dummyJson, function (d) {
return d.id === requiredID;
})
Get JSON object using JSON.parse('users.json') and store it in a variable users.
Loop through array of users using for .. in and using if condition on id update the object if required.
Stringify the updated users object using JSON.stringify(users); and write this string to users.json file using fs.write() module in NodeJS so you will have updated objects in your json file.

Microsoft.Graph Unable to deserialize the response

I am quite new to programming and especially Microsoft.Graph
I am having problems handling the response to:
https://graph.microsoft.com/v1.0/me/drive/root/children
the response looks like this (just much longer):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('xyz%40hotmail.com')/drive/root/children",
"value": [
{
"createdBy": {
"user": {
"displayName": "xyz",
"id": "cf58e4781082"
}
},
"createdDateTime": "2009-01-08T08:52:07.063Z",
"cTag": "adDpFREJDR4RTQMTgxMDgyITEyOC42MzYxODM0MTU0Mjc3MDAwMDA",
"eTag": "aRURCQ0Y1OEU0A4MiExMjguMA",
"id": "EDBCF58E471082!128",
"lastModifiedBy": {
"user": {
"displayName": "xyz",
"id": "edbcf58e48082"
}
}, ............. etc...
The response that I received is correct, in JSON format (I believe ><), but I cannot figure out how to parse it into an array containing the folders name.
Please help!
Have considered using the Microsoft Graph client library? It will deserialize the JSON. Your call will look like this:
// Return all children files and folders off the drive root.
var driveItems = await graphClient.Me.Drive
.Root
.Children
.Request()
.GetAsync();
foreach (var item in driveItems)
{
// Get your item information
}
Here's some samples to help you get started:
https://github.com/microsoftgraph?utf8=%E2%9C%93&q=csharp
You can use the JavaScriptSerializer to do this. Assuming
//json contains the JSON Response
var jsonOutput = new System.Web.Script.Serialization.JavaScriptSerializer();
jsonOutput.DeserializeObject(json);
This has been discussed earlier. See this thread: Easiest way to parse JSON response
Refer this link for JavaScriptSerializer: https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

React get JavaScript Object from JSON file?

The issue is that I'm trying to get a JavaScript object like the following:
[
"id" : 11,
"name" : "Peter"
"other": {
"id": 22,
"item": 534
},
"main": false
]
Since I want to get this via reactjs: I trying to do this:
http.get(API.BASE_URL + API.USER_INFO)
.accept('Application/json')
.end((err, res) => {
//console.log(x);
console.log(err);
console.log(res);
});
When I try a normal json string I get the right result, but with this javascript object I get:
Error: Parser is unable to parse the response
undefined
Has anyone come across this before? Any idea?
What you're trying to parse isn't valid JSON (as well as JavaScript) because you've written it out as an array, but still use key/value pairs as if it were an object. Try this instead:
{
"id": 11,
"name": "Peter",
"other": {
"id": 22,
"item": 534
},
"main": false
}