Json parse not convert to object - javascript

My API return user object and format is like that=>
{'id': '1', 'username': 'admin', 'image': 'https://user/testing.png', 'phno': '123'}
First I do JSON.stringify and I check the type of this line is a string.
So I use JSON.parse to get an object but its still string and can't get it likes user.id is undefined.
How can I get like user.id, user.username,...?
console.log(user);
console.log(user.user);
var test = JSON.stringify(user.user);
console.log(typeof(test));
var test1 = JSON.parse(test);
console.log(test1.id);

I think the problem might be that your API is returning JSON data with single quotation marks, and JavaScript is not able to parse it correctly. Check which JSON serializer you're using on server side. It should be like: {"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}.

This solution works for your data:
var data = '{"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}';
var user = JSON.parse(data);
console.log(user.id);

It seems like you are not getting exact user json. Issue may be backend.
const obj = `{"user":"{\\"id\\": \\"1\\", \\"username\\": \\"admin\\", \\"image\\": \\"https://user/testing.png\\", \\"phno\\": \\"123\\"}"}`
console.log(obj)
// First get value of user.
let user = JSON.parse(obj).user
console.log(typeof user) //string
// parse again, since user is string
user = JSON.parse(user)
console.log(user.username)
console.log(user.id)

Related

Unable to remove a key value pair from JSON string?

On doing console.log(data.toString()), I get the following output:
{
"cid":"9333227",
"status" : 30,
"user" : "user1"
}
On doing console.log(data['cid']) before performing delete, I get undefined as the output
I want to remove the cid key value pair such that the console.log(data.toString()) should generate the following output:
{
"status" : 30,
"user" : "user1"
}
I am doing delete data['cid'] and then doing console.log(data.toString()). However, it is still printing the original json
{
"cid":"9333227",
"status" : 30,
"user" : "user1"
}
If you run data.toString()), and get the output you got, means that data is not an object. It's likely a string.
If you run:
"hello".toString();
you get "hello".
If you run:
delete "hello".foo
You are deleting a non-existant property on the string, which works without error. It doesn't change the contents of the string.
So I think you don't have an object, you have a JSON string. To mutate it, you need to first parse it:
const obj = JSON.parse(data);
delete obj.cid;
console.log(obj);
If you need to turn it back into a JSON string, you can use JSON.stringify().
let jsonobj = {
"cid": "933227",
"status": 30,
"user": "user1",
}
delete jsonobj['cid']
console.log(JSON.stringify(jsonobj));
Try JSON.stringify() instead of .toString()

How to display a json get request where _something_ equals _anothersomething_ (Node.js, MongoDB)

I have an id inside req.params.id.
var id = req.params.id // let's say this is 2
And let's say I have this from MongoDB:
[
{
"text": "hello",
"fromId": "1"
},
{
"text": "hi",
"fromId": "1"
},
{
"text": "hey",
"fromId": "2"
},
]
I use this to query through:
const message = await Message.find().select('text fromId');
const fromId = await Message.distinct('fromId');
And I want something like this (but of course this code is incorrent):
res.json(message).where(id === fromId);
So I want to get only this because my id is 2 and fromId is 2:
{
"text": "hey",
"fromId": "2"
},
I want the get request res.json() to display only the ones where id is equal with fromId.
Pass a filter object to find function to fetch only those documents where fromId is equal to req.params.id
const message = await Message.find({ fromId: req.params.id })
I believe you're simply looking for
const message = await Message.findOne({"fromId": "2"})
You should also add .lean() so it returns simple JSON and is faster, and also .exec() to be non-blocking.
Full code :
const message = await Message.findOne({fromId: req.params.id}).lean().exec();
res.json(message);
Why are you not using Mongoose? If it's a personal preference to not use ORMs, I understand but if you do change your mind. It's as simple as
const message = await Message.findById(id); // This only takes mongoDB ids as arguments
// Use this for another general field
const message = await Message.findOne({fromId : id})
res.json(message).status(200);
You could also wrap it inside a try catch block to handle any errors if the document with the id wasn't found.

Is there a good framework or approach for restructuring JavaScript objects?

I am writing an application in Node.js. I need to convert JavaScript objects returned from my database layer to JavaScript objects that I need to return from my REST service. I may need to add or remove certain properties or perhaps flatten out some structures. For example, here's a User object returned from the database layer:
{
"id": 1234,
"username": "jsmith",
"person": {
"first_name": "John",
"last_name": "Smith"
}
}
The object that I want to return from the REST layer is
{
"_links": {
"self": { "href": "/users/jsmith" },
},
"username": "jsmith",
"firstName": "John",
"lastName": "Smith"
}
Here are the changes:
"id" property is removed
"links" section has been added
"person" object has been flattened out to the parent object
"first_name" and "last_name" properties have beed converted from snake_case to camelCase
I could obviously hand-code each one of these transformations, but that would be very inefficient and error prone. Do you know of any framework or approach that would ease this pain?
P.S. I am essentially looking for something similar to the Java framework called dozer.
You will need a custom function to convert the object returned from the DB before pushing them to the RESTAPI.
An example:
var dbObject = db.query(...); //this is what you get from your DB query
//Here is your REST API object that you will send back
var restObject = (function(obj){
var link = {
self: {
href: "/users/" + obj.username
}
};
var username = obj.username;
var firstname = obj.person.first_name;
var lastname = obj.person.last_name;
return JSON.stringify({
_links: link,
username: username,
firstName: firstname,
lastName: lastname
})
})(dbObject);
Obviously, this can be cleaned up/customized to fit your code (e.g: your DB query might be asynchronous, so the restObject will need to reflect that). Also, asssuming your DB sends back a JSON object, you will need to account for that.

how to handle document from mongoDB with _bsontype properties

Hi I'm walking through a JSON array resulting of a query of documents in mongoDB.
The fact is that I'm getting the following behaviour and I'm don’t know why I'm getting this:
in key: _bsontype |value: ObjectID
in key: id |value: S÷¯çò9þ w
in key: _bsontype |value: ObjectID
in key: id |value: S÷¯çò9þ h
in key: _bsontype |value: ObjectID
in key: id |value: S÷¯çò9þ h
in key: name |value: Default Process
in key: processType |value: Public
in key: id |value: BPMNDiagram_1
in key: name |value: procurement subprocess
As you can see, this is wear... this is my code:
function changeIDs(json, map, count){
for(var key in json){
if(json.hasOwnProperty(key))
if(typeof json[key] === 'object')
changeIDs(json[key], map, count);
else{
console.log("in key: "+key + " |value: "+json[key]);
}
}
}
And this is a part of my input ( json parameter ):
[
{
"_id": "538df78eafe7f28d39fe2077",
"processId": "538df71bafe7f28d39fe2068",
"processMeta": {
"id": "538df71bafe7f28d39fe2068",
"name": "Default Process",
"processType": "Public"
},
"diagram": {
"id": "BPMNDiagram_1",
"name": "procurement subprocess"
},
"plane": {
"id": "BPMNPlane_1",
"bpmnElement": "538df71bafe7f28d39fe2068"
}
},
{other objects..},{other objects..}
]
Yes, processId, and _id are generated with the ObjectId function, and seems here where the problem appears, I'm not sure about this, but my guess is that each _bsontype correspond to mongoSB Object Id and this is an object so my function go inside this recursively.. getting the following S÷¯çò9þ w..,Am I right ?
Also seems like if I'm not able to get the "processId" and "_id" keys in my for, because of that, I guess are my _bsontype...
So at the end, my question is, How can I walk through my object without getting that results ?, you have to see there is an "id" property that contains crap data and I don’t want it in my result when looking for all keys id for example, BUT still be able to get the ObjectId.str value for my properties "processId" or "_id".
Thanks in advance.
Just in case, if in the future some other unlucky guy as me get the same problem.
As you can see my function changeIDs get 3 parameters, I just change the json parameter, it was supposed to be a json ( and it was ) you can see my json output as text in my question, so it is a valid json, however I did a parse of a stringify string.. and after that I try it again.. and it was working.
So the solution? newJson = JSON.parse(JSON.stringify(json));
Why? well my better bet is that in this way, when we do a stringify of an object, it object change in the following way:
Undefined values disappear in the result.
Lose prototypes properties
The functions die
For example if a json have an object DATE this object would be stringify as Date.toString(), so it would storage the string representation. and if the function does not have a to string would be undefined.
This last is why after doing an stringify it is working, My function ObjectId() didn't survive to my stringify, but it transform to the string value it contains, that is the Mongo object id value...

Adding to a JSON string

I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});

Categories

Resources