-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"}
  • Tried this in chrome js console, and displays correctly there :/ – Nsevens Apr 01 '19 at 20:24
  • Agree with @Nsevens – razki Apr 01 '19 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. – Tarra Lawless Apr 01 '19 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. – AuxTaco Apr 01 '19 at 20:42
  • Recursively? Not sure what you mean. I am shown a string in the console. – Tarra Lawless Apr 01 '19 at 20:45
  • I have tried moving this exact script around in my file, and I still get the same result. I get the result I'm looking for when I try it in a codepen though. Is there something inside my php file that could cause this different result? – Tarra Lawless Apr 01 '19 at 21:06

1 Answers1

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.