2

Here is my typescript object:

{
      first_name:"test",
      last_name: "test",
      birthdate:"2018-01-08T16:00:00.000Z",
      contactNumber: "12312312312",
      email:"test@test.com",
      username:user."test",
      password: user."test"
}

VS

{
    "first_name":"test",
    "last_name": "tests",
    "birthdate":"2018-01-08T16:00:00.000Z",
    "contactNumber": "31231232131",
    "email":"email@gmail.com",
    "username":"test",
    "password":"test1234"
}

Every time I send it via HTTP POST using Angular 5. There's always an error on my API side.

Here is the error.

Unpermitted parameters: :first_name, :last_name, :birthdate, :contactNumber, :user

When I add double quotes to all keys it works fine.

Randz67
  • 817
  • 1
  • 9
  • 13
  • 3
    Don't mix JavaScript objects (which are the same as Typescript objects) with JSON – Pac0 Jan 10 '18 at 14:17
  • @Pac0 so with passing data to API instead of passing the object(Typescript Object) I will create a json object and just populate it. Is that acceptable? Thanks! – Randz67 Jan 11 '18 at 08:54
  • 1
    That is the exact usual way to do it. There is no difference between Typescript and Javascript in this. In Angular5, if you use HttpClient to do your requests, the serialization / deserialization between JSON and actual javascript code object is already done for you. https://angular.io/guide/http#httpclient . Otherwise you should use JSON.stringify(yourObject) https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string – Pac0 Jan 11 '18 at 09:43
  • 1
    also, as another answer already states, a JSON is a string, and has to be surrounded by quotes. – Pac0 Jan 11 '18 at 09:44

2 Answers2

1

According to the JSON specs (see http://json.org) you have to surround the keys with double quotes.

A JSON object contains a set of string/value pairs, and strings are defined as follows:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

That is so you can use reserved keywords as keys, as in

{
    "function": "sqrt"
}

Basically, "JSON" code where the key is not surrounded by double quotes is not valid JSON.

mrx
  • 26
  • 3
0

The answer is in the first drawing on the JSON website: object keys must be encoded as strings in JSON. If they are identifiers (not strings) then it is not JSON but a literal Javascript object.

It seems the Ruby library that processes the API requests understands correctly the data you send (a Javascript object) and converts the keys to Ruby symbols. The validation code expects the keys to be strings (as they are decoded from a valid JSON), hence the error message.

axiac
  • 68,258
  • 9
  • 99
  • 134