Friday, April 29, 2011

JSON: How do I store a string with a " in it?

I want to have a JSON object with the value of an attribute as a string with the character " . For example { "Dimensions" : " 12.0" x 9.6" " }

Obviously this is not possible. How do I do this? With python.

From stackoverflow
  • JSON.stringify, if using Javascript, will escape it for you.
    If not, you can escape them like \" (put a \ in front)
    Edit: in Python, try re.escape() or just replace all " with \":

    "json string".replace("\"","\\\"");
    
  • Isaac is correct.

    As for how to do it in python, you need to provide a more detailed explanation of how you are building your JSON object. For example, let's say you're using no external libraries and are doing it manually (ridiculous, I know), you would do this:

    >>> string = "{ \"Dimensions\" : \" 12.0\\\" x 9.6\\\" \" }"
    >>> print string
    { "Dimensions" : " 12.0\" x 9.6\" " }
    

    Obviously this is kind of silly. If you are using the standard python json module, try this:

    from json import JSONEncoder
    encoder = JSONEncoder()
    string = encoder.encode({ "Dimensions":" 12.0\" x 9.6\" " })
    
    >>> print string
    {"Dimensions": " 12.0\" x 9.6\" "}
    

    which is the desired result.

    kigurai : +1 for using libraries to do the job
  • Python has two symbols you can use to specify string literals, the single quote and the double quote.

    For example: my_string = "I'm home!"

    Or, more relevant to you,

    >>> string = '{ "Dimensions" : " 12.0\\\" x 9.6\\\" " }'
    >>> print string
    { "Dimensions" : " 12.0\" x 9.6\" " }
    

    You can also prefix the string with 'r' to specify it is a raw string, so backslash escaped sequences are not processed, making it cleaner.

    >>> string = r'{ "Dimensions" : " 12.0\" x 9.6\" " }'
    >>> print string
    { "Dimensions" : " 12.0\" x 9.6\" " }
    
    David Berger : Good point about using raw strings.

0 comments:

Post a Comment