最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I wrap my serialized JSON string in 'single quotes' - Stack Overflow

programmeradmin0浏览0评论

I have a javascript object called blocki that I want to serialize and update using a rest API. So I call:

JSON.stringify(blocki)

And that gives me this string:

"{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}"

That is almost what I need, except the doubly quoted string should have single quotes on the outside, like so:

'{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}'

According to examples on MDN JSON.stringify it should return an string wrapped in single quotes. But when I try the same example in that page, I get string wrapped in double quotes. For instance, when I type JSON.stringify({}) in Firefox and chrome console, I get back "{}" instead of '{}'.

How can I properly serialize my Javascript object so the outer quotes are: '. Again, this string is an example of what I want to achieve:

'{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}'

Ideally, I would like to learn an nice way to serialize the object instead of having to modify the string after serialization.

Edit: The reason I think I need to do this is that the API I am working with is somehow not happy when the string is wrapped in double quotes. For example when I do

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d "{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}" 'http://localhost:3000/api/blockies/17'

The request fails and server gives a parsing error. However when I try:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d '{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}' 'http://localhost:3000/api/blockies/17'

The put request goes through successfully and the object is updated.

I have a javascript object called blocki that I want to serialize and update using a rest API. So I call:

JSON.stringify(blocki)

And that gives me this string:

"{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}"

That is almost what I need, except the doubly quoted string should have single quotes on the outside, like so:

'{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}'

According to examples on MDN JSON.stringify it should return an string wrapped in single quotes. But when I try the same example in that page, I get string wrapped in double quotes. For instance, when I type JSON.stringify({}) in Firefox and chrome console, I get back "{}" instead of '{}'.

How can I properly serialize my Javascript object so the outer quotes are: '. Again, this string is an example of what I want to achieve:

'{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}'

Ideally, I would like to learn an nice way to serialize the object instead of having to modify the string after serialization.

Edit: The reason I think I need to do this is that the API I am working with is somehow not happy when the string is wrapped in double quotes. For example when I do

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d "{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}" 'http://localhost:3000/api/blockies/17'

The request fails and server gives a parsing error. However when I try:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d '{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}' 'http://localhost:3000/api/blockies/17'

The put request goes through successfully and the object is updated.

Share Improve this question edited Jan 24, 2016 at 20:16 jedierikb 13.1k23 gold badges101 silver badges170 bronze badges asked Nov 5, 2012 at 21:47 ArasAras 5,9269 gold badges51 silver badges79 bronze badges 5
  • why do you need to wrap the json string? adding quotes like makes it an invalid json string to begin with. – Marc B Commented Nov 5, 2012 at 21:48
  • A string does not retain the information of whether it was declared with double or single quotes (assuming it was declared at all). '"' and "\"" are equivalent as far as JavaScript is concerned. – zzzzBov Commented Nov 5, 2012 at 21:53
  • ok I updated my post to who why I thought there was a difference between single and double quote string – Aras Commented Nov 5, 2012 at 21:56
  • You shouldn't be making the call to Curl in such a way that the outer quotes matter. If you're making a shell call to Curl (you didn't say which language you were using) you should (for security reasons) be using a call where the parameters are passed as an array (without delimiters) and not as a single string. – Alnitak Commented Feb 17, 2016 at 8:49
  • can someone answer the actual question? in my case I need single quotes. – tanner burton Commented Jan 3, 2022 at 23:18
Add a comment  | 

5 Answers 5

Reset to default 7

You don't need those single quotes wrapping the string - those are only there on the MDN page to show the string literals that correspond to the output.

The quotes are not part of the content of the strings themselves!

EDIT - you've edited the question since I wrote the above.

The simple answer is that if you absolutely must wrap the string in single quotes yourself, just use:

var json = "'" + JSON.stringify(obj) + "'"

The longer answer is still that you shouldn't be wrapping the string at all. It's considered bad practise to pass entire command lines to a shell - the presence of certain environment variables (especially IFS) can change the way that the command line is interpreted, leading to security issues.

Since you're using Javascript I guess perhaps you're using nodejs and the child_process module? If so, you should be using .spawn instead of .exec, and passing the parameters as an array. When passed this way the parameters are passed directly into Curl's argv array without being parsed by the shell first, and therefore need no quoting at all, e.g.:

var child = spawn('curl', [
    '-i', '-H', 'Accept: application/json',
    '-H', 'Content-type: application/json', 
    '-X', 'PUT',
    '-d', json,
    'http://localhost:3000/api/blockies/17'
]);

or better yet make the PUT call directly from Node without using Curl.

There are no differences between strings wrapped in single or double quotes, besides escaping which is done automatically by the JSON.stringify method. The single/double quotes which wrap string literals are not part of the string itself.

Double quotes is the way Firefox and Chrome prefer to represent string literals in the console.


Edit: Now with the CURL command it changes the meaning of the question completely.

"{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}"

The string above is not a valid string as you can't have unescaped double quotes inside a double quote-wrapped string.

What you're seeing is just an artifact of how the console prints the string.

To wit, try this in Chrome's Console for fun...

JSON.parse(
  JSON.stringify(
    JSON.parse(
      JSON.stringify(
        JSON.parse(
          '{"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}}'
))))).name

For instance, when I type JSON.stringify({}) in Firefox and chrome console, I get back "{}" instead of '{}'.

This is how strings are displayed in console. It's actually not "{}" but a string that contains {}. Quotes are just to signify that it's a string. Try typing '' in Chrome console and you'll see what I mean.

The surrounding single/double quotes are just indicator that it is a string, it's not part of the actual String data and can't be stored.

var serializedData = JSON.stringify({"name":"Updated Blocki","bounds":{"x":"2em","y":"2em","w":"8em","h":"12em"}});
var deserializedData = JSON.parse(serializedData);  // whether console displays the serializedData String with single or double quotes is irrelevant

If you are storing the String and outputting it to the client side, wrap it with single quotes as you've done.

Is there anything that prevents you from wrapping it with single quotes when using curl?

If you insist on wrapping it with double quotes, you have to escape the double quotes in your string like so:

"{\"name\":\"Updated Blocki\",\"bounds\":{\"x\":\"2em\",\"y\":\"2em\",\"w\":\"8em\",\"h\":\"12em\"}}"
发布评论

评论列表(0)

  1. 暂无评论