3

I have created an interface of User to put in some value from ngModel. Take a look at this.

user.ts

export class User{
    _id: String;
    username: String;
    password: String;
    firstname: String;
    lastname: String;
    gender: String;
    address: String;
    contact: Number;
    email?: String;
}

Example of ngModel binding

<input type="text" [(ngModel)]="user.username" class="form-control" name="username" id="username" placeholder="Enter your Username" formControlName="username"/>

Output from the console log

enter image description here

I want to make the result to a json. I use JSON.parse but the error on the title pops up. How can I convert it to a json object? Thanks

1 Answer 1

5

JSON.parse is meant for creating a javascript object from a string (that is already formatted for JSON). What you're looking for is JSON.stringify instead to convert your javascript object into JSON text.

Sign up to request clarification or add additional context in comments.

6 Comments

i think this is a dumb question but do you consider the User to be a JSON object?
@MixAustria there's no such thing as a "JSON object" in JavaScript. Your user type is simply an object, and any JavaScript object can be turned into a JSON string.
User is a javascript object in this case. JSON is "Javascript Object Notation", which is a text-based format to represent objects in javascript (many great definitions out there to learn more about the difference)
JSON text would be a string in Javascript that represents the User object, such as "{ _id:'1', username:'abc' /**... and so on ...**/ }"
now I pass this object to an express server and here is what I got on the request body. kindly see this please prntscr.com/dkfgwy There are \n on the object and I cannot access it for example req.body.username etc. can you tell my why?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.