Not able to get value from Json key - json

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");
});

Related

typescript - load json from url and get access to array of json objects

I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}

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);
}

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

Json manipulation TypeScript Angular 2

I come from a Python Background and recently started programming using TypeScript and Angular2. I want to know how to obtain keys from a JSON object using TypeScript.
I have a response like so:
response.text()
I pass this object to a function
removeMetaData (my_data: string){
//(Various manipulation)...etc
}
i have read that I can call a json() method instead of text(). If I do that, what is the type I should use for my_data?
Then,
If my JSON looks like this:
{
"count": 100,
"next_page": "http://www.test.com/users/?page=2",
"prev_page": "http://www.test.com/users/?page=3",
"results":[
{
"username": "johnny"
},
Etc....
]
How do I parse that?
I've read I might have to use an interface but I don't understand how.
In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. That is exactly what I'm trying to achieve within a component.
Thank you.
ADDITION
list() {
this.requestService.get(this.api_path)
.subscribe(
response => this.populate(response.json()),
error => this.response = error.text()
)
}
populate(payload: object) {
this.count = payload.count;
this.next = payload.next;
this.previous = payload.previous;
*payload.results => this.users = payload.results;******
}
Declare an interface which will be used as value object.
export interface IPage
{
count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}
var my_data:IPage;
Now assign parsed json value to my_data and access all the properties with '.' operator i.e. my_data.count, my_data.results.
Feel free to throw any question.
If I do that, what is the type I should use for my_data?
Its just a javascript object.
As an example if you json looks like:
{
"foo": {
"bar": "bas"
}
}
Then in the parsed json (in variable someObj) the value someObj.foo.bar would be bas 🌹

How to access values in a multidimensional JSON array from backgrid template

I am trying to get json value from laravel json response to Backgrid template
My laravel json response is
return Response::json(
array(
'items'=> $articles->toArray()
));
It response json array like these
{"items":[{"id":30,"title":"Tester","body":"tesrter","user_id":566,"user_nickname_id":0,"category_id":1,"community_id":0,"ref_link":"face.com","status":3,"points":0,"editor_id":566,"created_at":"2015-03-21 15:53:43","updated_at":"2015-03-21 09:23:43","category":{"id":1,"name":"Cupcake wrappers","description":"","created_to":"2015-02-27 13:53:15","updated_to":"0000-00-00 00:00:00"}}]}
My backgrid cell is
var CateoryType = Backgrid.Cell.extend({
template: _.template('<%=category.name%>'),
render: function () {
this.$el.html(this.template( this.model.toJSON() ));
this.delegateEvents();
return this;
}});
But I couldn't get category 's name from json response.
How Could I get Category name from my Backgrid Cell or any other way to access it?
the problem being you are not returning an exact collection from your laravel, you can do it in either using backbone or laravel(optimal)
instead return just say
echo json_encode($articles->toArray());
Using backbone parse method:
in your collection use
parse : function(response){
return response.items
}