Search code examples
pythonpython-2.7jsonpnewlinestring-formatting

Python 2.7: String formatting for JSONP


I have two scripts that are called separately, Script 1 calls Script 2 and the output of both is returned. The result is a JSONP string, which has a newline character caused by Script 2 adding a new line in the end of print.

I'm running Python 2.7.10. I usually get one of these errors when executing the second script:

TypeError: expected a character buffer object or invalid syntax for using Python 3 commands.

How do I make sure that there is no newline character in the resulting string?

Script 1 (Script 2 call):

jsonstring = subprocess.check_output(['python',"scripts/"+path+'.py'],shell=False)
return "%s(%s)" % (request.query.callback, jsonstring)

Script 2:

import json
def func():
    jsonString = \
        """[ 
            { "DT_RowId": "row_1", "size": "medium", "color": "red" },
            { "DT_RowId": "row_2", "size": "large", "color": "blue" },
            { "DT_RowId": "row_3", "size": "medium", "color": "white" }
        ]"""
    print(jsonString), #end="", flush=True) Available from Python 3
func()

Resulting string:

jQuery111306445024223066866_1447346051405([{'size': 'medium', 'color': 'red', 'DT_RowId': 'row_1'}, {'size': 'large', 'color': 'blue', 'DT_RowId': 'row_2'}, {'size': 'medium', 'color': 'white', 'DT_RowId': 'row_3'}]
)

Solution

  • For script 2, please try:

    from __future__ import print_function
    

    and then use print function without \n in end of line

    print(jsonString, end='')
    

    Related doc: https://docs.python.org/2/whatsnew/2.6.html#pep-3105-print-as-a-function