JSON.Stringify Adds Quotes To ID [duplicate]

2019-08-12 15:25发布

问题:

This question is an exact duplicate of:

  • BackboneJS Make ID Integer

I'm using JSON.stringify and JSON.parse to edit my JSON file based on changes to an online database. Everything works right, except it is making quotes around a number which is screwing up the JSON file. For example it should be "id": 1 but it is printing out "id": "1". How would I edit the quotes out? I prefer to use JSON.stringify and not an alternative.

回答1:

if you are getting the number from input field, the number or whatever input is always string and therefore its quoted.

To fix that you should add parseInt() for your input values like:

var value = parseInt($('#fieldID').val());

Hope that helps



回答2:

1 must not be a true integer to begin with. Executing JSON.stringify({id: 1}) in the console will return "{"id":1}". How are you defining the value for id? I'm guessing at that point, it is getting saved as a string (i.e. {id: "1"}).