Why does Axios.get give me an [object Object] - mern

I'm trying to get a JSON object into an array to show on a table, however it gives me the error of: TypeError: this.state.allVersions.map is not a function.
componentDidMount()
{
axios.get('http://localhost:5000/myblog/' + this.props.match.params.id).then(res =>
{
console.log(res.data);
this.setState({allVersions: res.data});
console.log(this.allVersions)
}).catch((err) =>
{
console.log(err);
})
}
Here I'm trying using the endpoint to get a JSON object and on the first console log, it gives me the right data but on the second console log it gives me [object Object].
Also,
{console.log("state of all versions: " + this.state.allVersions)}
gets me an [object Object] but if i do
{console.log(this.state.allVersions)}
it gets me the right data? Why is removing the string doing this?

Concatenation of string and object would make object be converted to a string, not to a JSON.
Instead you would want to convert your object to JSON before concatenation.
so in your code it will look like
console.log("state of all versions: " + JSON.stringify(this.state.allVersions))

Related

Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid JSON

I am not sure whether my function is wrong, which should send data to the server, or the function on the server is wrong.
I looked up similar questions but the solution I adopted to my problem did not work.
My function looks like this:
postData(number){
let array = JSON.stringify(this.locArr);
return this.http.post<any>(this.url, array)
.subscribe(),
error => console.log("Error: ", error)
}
JSON which is send:
[
{
"id":222,
"name":"Lars",
"sLA":37
},
{
"id":223,
"name":"Sim",
"sLA":12
}
]
All parameters like token etc. are received by the server function but the array I wrote above is null, although it is valid json.
I wonder why this error is occuring.
Any advice is appreciated
The local array will be converted into JSON automatically by Angular, you need not stringify or parse it.
postData(number){
this.http.post<any>(this.url, this.locArr)
.subscribe((data)=>{
//code after receiving data from server
},
error => console.log("Error: ", error))
}
I believe you are using httpClientModule so then there is no need of tyou need't JSON.stringify remove this step JSON.stringify(this.locArr);
Also you need to send it as json object {} not json array []
postData($locArr){ // pass the array to the service function
let data = { data : $locArr}; // note that you have to post it as json object {} not []
return this.http.post<any>(this.url,data);
}

Filter json objects

Some of my logs contain json in their message field. I use the json filter as follow:
json {
skip_on_invalid_json => true
source => "message"
target => "json"
}
To try to parse the message field, and if it contains valid json add it to the json field.
Unfortunately from time to time, I receive logs which contain a single string like "some random message" in the message field. In these logs the string from message end-up in the json and messes up the index mapping.
I htried to filter this out by adding:
prune {
blacklist_values => { "json" => "/.+/" }
}
But this seems to always remove the json field.
Is there a way to parse the message field or keep the json field only when it contains an object and not a single string?
You could do it using a ruby filter that tests the field you are interested in
ruby {
code => '
s = event.get("json")
if s and s.instance_of? String
event.remove("json")
end
'
}
That will not remove [json] if it is a hash or array.

parse json response to typescript class

i know there are multiple similar topics, however trying their solutions doesn't give me expected result.
Input json string
data:"{"message": "{\"type\":\"CONTROL\",\"command\":\"REQUEST_STATUS_ALL\"}"}"
object declaration/parse:
const msg: Message = <Message>JSON.parse(data.data);
output:
{message: "{"type":"CONTROL","command":"REQUEST_STATUS_ALL"}"}
-values are not properly assigned, but instead in a text form.
the same object looks like this if it's initialized manually(in TS):
MessageĀ {type: "CONTROL", status: undefined, command: "REQUEST_STATUS_ALL", body: undefined}
What is the correct way to parse that json string into the Message object?
Thank you!
It seems the value for message was improperly encoded as a string. Calling JSON.parse a second time on the message property will get the result you want, though you might want to fix the underlying cause of the improperly encoded data instead.
parseMessage(data: string) {
const msgTemp = JSON.parse(data);
msgTemp.message = JSON.parse(msgTemp.message);
return <Message>msgTemp;
}
const msg = parseMessage(data.data);

Not able to get value from Json key

I am trying to get an object from Mongoose but when I get it and try to access the Json object by key to get the value i get undefined.
User.find({name: 'auth'},function (err,obj) {
var authCode = JSON.stringify(obj);
console.log(authCode);
var parse = JSON.parse(authCode);
console.log(parse);
console.log(parse.code);
});
I get the following output:
[{"_id":"5a43b491734d1d45eaf2d00d","name":"auth","code":"nCAxOSrUMqxtxd8T"}]
[ { _id: '5a43b491734d1d45eaf2d00d',
name: 'auth',
code: 'nCAxOSrUMqxtxd8T' } ]
undefined
I have even tried console.log(parse['code'])and i still get undefined. Can someone please help me
parse variable above is not a dictionary itself, but an array containing a dictionary. What you should do to access the code field would be first access the dictionary and then get the code field like;
parse[0].code
or
parse[0]['code']
You need not parse or stringify the returned JSON object. You can use the JSON object as it is. Try below approach
User.find({name: 'auth'},function (err,obj) {
console.log(obj);
console.log(obj.code);// this will probably be undefined as find method returns array of objects ( correct me if iam wrong)
user.forEach(function(obj,index){
console.log("index: "+index);
console.log("obj: "+obj.code);
});
});
Using promises is a good way
User.find({name: 'auth'})
.then((user)=>{
console.log("find success");
console.log(user);
console.log(user.code); // would return undefined as User.find will return array of objects
user.forEach(function(obj,index){
console.log("index: "+index);
console.log("obj: "+obj.code);
});
})
.catch(()=> {
console.log("find failed");
});

json value getting it as "[object Object]"

In angularjs ng-route since my params are dynamic i'm passing it as json like as shown below
$scope.filmNames= {
'films': {
'film': [{
filmName: 'ABCD',
filmYear: '123'
}, {
filmName: 'BCD',
filmYear: '145'
}, {
filmName: 'DEF',
filmYear: '128'
}]
}
};
'.../index.html#/admin?jsonObj='+$scope.filmNames
ans it succesffully sending as like
http://localhost:8000/index.html#/admin?jsonObj=[object Object]
but at the controller receiver when i tried to get it through using $routeParams like
var jsonObj= $routeParams.jsonObj;
console.log(JSON.stringify(jsonObj));
It is been printing it as "[object Object]", instead of the values
can anyone please tell me solutions for this
When you convert an object to a string using concatentation, you get: [object Object]. What you actually want is to convert the object to json.
'.../index.html#/admin?jsonObj='+JSON.stringify($scope.filmNames)
Then, at the receiver, you'll want to parse it, not stringify it.
console.log(JSON.parse(jsonObj));
I suggest moving away from calling json strings "json objects", it just leads to confusion. json strings don't always represent objects.