-1

I'm getting a bad response when i post a json.stringify via fetch, and the problem is from escaped quotes that json.stringify is producing. It works when I remove them manually, but I need this to be done automatically.

var order = {
  "from_country": "US",
  "line_items": [
  {
  "quantity": 1,
  "unit_price": 19.95
  }
  ],
  "to_country": "US"
};

var body = JSON.stringify(order);

var body will display as:

{"from_country":"US","line_items":"[{\"quantity\": 1, \"unit_price\": 19.95}]","to_country":"US"}

I'd like it to display as:

{"from_country":"US","line_items":"[{"quantity": 1, "unit_price": 19.95}]","to_country":"US"}
6
  • Tried this in chrome js console, and displays correctly there :/ Commented Apr 1, 2019 at 20:24
  • Agree with @Nsevens Commented Apr 1, 2019 at 20:25
  • My output is directly from the chrome console. Perhaps this is an issue with my JavaScript being wrapped inside PHP then, thank you, I'll look into that. Commented Apr 1, 2019 at 20:35
  • Are you stringifying order recursively? As the first snippet is written, order doesn't stringify like that: order.line_items is an array, but you claim the result is a string. Commented Apr 1, 2019 at 20:42
  • Recursively? Not sure what you mean. I am shown a string in the console. Commented Apr 1, 2019 at 20:45

1 Answer 1

0

The issue was that my file includes the prototype library.

I fixed the conflict, while still maintaining the functionality(I think) of prototype by adding this code -

JSON = JSON || {};
JSON.stringify = function(value) { return Object.toJSON(value); };
JSON.parse = JSON.parse || function(jsonsring) { return jsonsring.evalJSON(true); };

I first stumbled on this being the problem here:https://stackoverflow.com/a/20331694/8326722 which led me to https://stackoverflow.com/a/1327371/8326722 and then I added the bit from a comment to get it to work with objects.

If someone can explain how the code I'm using works, that would be nice.

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

Comments

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.