How can I put double quotes inside a string within an ajax JSON response from php?

前端 未结 3 1746
天涯浪人
天涯浪人 2020-12-05 04:18

I receive a JSON response in an Ajax request from the server. This way it works:

{ \"a\" : \"1\", \"b\" : \"hello \'kitty\'\" }

But I did not succeed in put

相关标签:
3条回答
  • 2020-12-05 04:45

    A little off-topic, you could use JavaScript/NodeJS on your server and use ES6 template literals (the backticks `` used around "Christian"), but 7 years later you probably already use NodeJS :)

    var myJSON = {
        "name": {
            "first": `"Christian"`,
            "last": "Broberg"
        },
        "age": 49,
        "skills": [ "JavaScript", "React", "NodeJS" ],
        "married": false,
        "superpowers": null
    }
    
    0 讨论(0)
  • 2020-12-05 04:57

    use just json_encode (any PHP element ), it will automatically parses.

    0 讨论(0)
  • 2020-12-05 05:03

    Just escape it with a backslash:

    > JSON.stringify({"a": 5, "b": 'a "kitty" mighty odd'})
    {"a":5,"b":"a \"kitty\" mighty odd"}
    > JSON.parse('{"a":5,"b":"a \\"kitty\\" mighty odd"}')
    Object
      a: 5
      b: a "kitty" mighty odd
      __proto__: Object
    

    JSON parsers recognize \" inside double-quoted strings as a double quote. Note that in the second example, the double-backslash is needed because there's a Javascript parser pass, then another JSON parser pass.

    0 讨论(0)
提交回复
热议问题