How to get specific field from Json file in Angular? [duplicate] - json

This question already has answers here:
Difference between JSON.stringify and JSON.parse
(17 answers)
Closed 8 months ago.
this.http.post(this.url + "/DeptWiseCount", {
startDate: this.newStartDate,
endDate: this.newEndDate
}).subscribe(
data => (
this.response = JSON.stringify(data),
console.log(this.response + data[0]["port_count"])
),
error => (
this.handleError(error)
)
)
In the above code I am simply want to get data from the API in my console log but it throw an error i.e. Cannot read properties of undefined (reading 'port_count'). I don't know why? Please help me. API output as mention below:
{
"data": [
{
"key": "Pending",
"total_count": 576871,
"traffic": 2,
"traf_count": 502045,
"port": 1,
"port_count": 74826
},
{
"key": "Cash",
"total_count": 305414,
"traffic": 2,
"traf_count": 245316,
"port": 1,
"port_count": 60098
}
]
}
Thank You

JSON.stringify() is used to convert an object into json string. In your
case you shoud be using JSON.parse() to generate a js object from a json response. Hope this helps

Related

Angular POST method send only a JSON array

I have an Angular frontend which communicates with a Spring REST API. The Spring endpoint expects a JSON array, but with Angular HttpClient POST method I don't know how to send only a JSON array. Now I get HTTP error code 400 (Bad request).
What I need to send to the endpoint (this is tested and works in an API tester):
[
{
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
{
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
]
The way I'm sending the changes now:
modifyElements(id: number, elements: Element[]): Observable<Element[]> {
return this.http.post<Element[]>(this.baseUrl + '/modify/' + id, elements);
}
The structure of the data that is sent by HttpClient's put method is below:
{
"0": {
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
"1": {
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
}
What I also tried and is closer to what I need:
this.http.post<Element[]>(this.baseUrl + '/modify/' + id, {elements: elements});
What this sends:
"elements": [
{
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
{
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
]
This is still not accepted by the API, results in the same error.
Please help me how can I send the data in the right structure, only a JSON array.
I already know how can I workaround this issue in Spring: in the controller method expecting for a request body of a new class that has just one member which is a collection, but that's not a nice solution.
I would like to know how it can be done without a workaround, on the Angular side.
Edit:
Thank you for the answers so far, but they return the same array I had, with the same structure.
The data structures I inserted in the question are the request bodies sent by Angular's HttpClient, copied from Chrome DevTools.
I think the problem is not with my original array, but with how HttpClient creates the JSON that it sends.
It seems to me that it can't interpret an array as a simple JSON array, and can only send a JSON array as a key-value pair, the value being the JSON array.
What I need instead is to get rid of the key and send only the plain value.
The question is, can HttpClient do that?
I faced the same problem, and I resolved with:
return this.http.request<ReturnType>(
'POST',
URL,
{
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: JSON.stringify(array)
});
Use this snippet
modifyElements(id: number, elements: Element[]): Observable<Element[]> {
const elementsArray = Object.assign([], elements);
return this.http.post<Element[]>(this.baseUrl + '/modify/' + id, elementsArray );
}
This will convert to the required format
var a ={
"0": {
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
"1": {
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
}
var c = Object.assign([], a)
console.log(c)
as I see you have object type [key:value] ,key is index value is an element entity. you have to extract values from this object and then send it to the server
Object.values(elements) //send this

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
}

Posting data in a JSON file in AngularJS - (using django REST here to create that JSON file.)

I am using AngularJS along with Python & Django and Django REST API.
There is a JSON file created by the REST API and I need to post data into it using Angular $http.post().
I need to know if it is possible or not.
Im majorly getting 403(Forbidden) and 400(BAD REQUEST) errors on post..
$http({
method: 'POST',
url: '<JSON FILE URL>',
data: $scope.tmpDataSet,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}});
This is my .post() method. where im fetching the data from a form made in angular and storing it in 'tmpDataSet'. Its being created properly and im able to store into the array.
Im just not able to write it into the JSON file.
The structure of my JSON file is
{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"name": "fff",
"mobile_no": "fff",
"email": "n#gmail.com",
"message": "dfdf",
"id": 1
},
{
"name": "asd",
"mobile_no": "0987654321",
"email": "asd#gmail.com",
"message": "no",
"id": 2
}
]
If any more code detail is needed please comment.
This issue was solved by adding CSRF tokens to the angular app and using the regular $http.post() function with all the parameters.
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
and,
$http.post('<URL>', item).error(function(data,status,headers,config){
console.log('COULDNT POST!');
}).success(function(data, status, headers, config){
console.log('POSTED!');
});

Using JSON.parse for accessing a json file

jQuery Code:
$(document).ready(function(){
$.getJSON('dat.js', function(data) {
var obj = JSON.parse(data);
alert(obj[0].title);
});
});
My JSON file :
{
"posts":
[
{
"title": "ajax | Programming ",
"url": "hello"
},
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
},
]
}
Its giving me an error JSON.parse:unexpected character. But when I tried to do it by taking the json inside an array its ok then. I want to access the data from json file itself
you do parseJSON when your input is a json string and u expect an object. Here, getJSON is already giving u the response as an object.
try this
$(document).ready(function(){
$.getJSON('dat.js', function(obj) {
alert(obj.posts[0].title);
});
});
A Quick jslint check says that you have invalid json at line 11 },, Try removing the comma from the last member of "posts" and see if that help
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
}, <---- THIS

JSON Parsing Error

I got problem. I have this JSON automatically generated by Open Flash Chart php library. The problem is, OFC report JSON Parse Error [Syntax Error] while test result using http://www.jsonlint.com/ report that my JSON is fine. But, w3c parser report error too:(
Any help?
Here's the JSON:
{
"title": "Followers Trend",
"elements": [
{
"type": "area_hollow",
"fill-alpha": 0.35,
"values": [
],
"colour": "#5B56B6",
"text": "Followers",
"font-size": 12
}
],
"x_axis": {
"colour": "#A2ACBA",
"grid-colour": "#D7E4A3",
"offset": false,
"steps": 4,
"labels": {
"steps": 2,
"rotate": "vertical",
"colour": "#A2ACBA",
"labels": [
]
}
},
"x_legend": {
"text": "Week Trend (2009-08-17 - 2009-08-24)",
"style": "{font-size: 20px; color: #778877}"
},
"y_axis": {
"min": 0,
"max": 150,
"steps": 30
}
}
A few things I learned while playing with JSON is:
If you have validate the JSON on various JSON validation services and the result is GOOD. But, when you failed to eval it, try to wrap your JSON using ( and ) => ({jsondata})
var json = eval( "(" + jsonString + ")" );
NEVER build the JSON yourself. It's a gate to failure. Always use official or popular JSON library (depending on your language). For example:
On PHP: use json_encode()
On Java Android: use org.json.JSONObject
A list of all other available library to play with JSON is listed in JSON official page.
To display and format JSON data, you can use JSONViewer.
I think the w3c parser is having issues, I couldn't even get it to parse this:
{
"title" : "Followers Trend"
}
It gave me this error:
Validation errors:
lexer couldn't parse at "{
"title" : "Followers Trend"
}"
http://json.bloople.net helps you visualise the code to find and correct errors.
try this code, JSON.parse() method is not able to handle string which is in a
single quote as a value in the right-hand side. also if you want to handle the
UTF-8 character code, then it will do.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
console.log(data)
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}