Encode Javascript variable name in Python JSON

I am writing a program that generates JSON and outputs it to the file. The first content that I output to the file is the following JSON string:

var jsonStyle = {'color': '#004070',
    'weight': 2,
    'opacity': 0.9}

Then I use the Python JSON library to generate JSON output. This is the Python object that I pass into json.dumps :

js = {'type': 'Feature',
      'properties':
          {'style': 'jsonStyle'},
      'geometry': geomJSON}

What I want the text output to be is:

js = {'type': 'Feature',
      'properties':
          {'style': jsonStyle},
      'geometry': geomJSON}

This way I can edit jsonStyle at the top of my output file to change the style for all subsequent JSON elements. The issue is, the current way I structure the JSON object outputs 'jsonStyle' , which is a string, not the Javascript variable name. If I instead set the style key to a dictionary version of the style string I output, it will include that JSON object for every subsequent JSON element. I don't know how to let style reference a Javascript variable name when I encode it in Python.

I would prefer not to have to do string manipulation for this, but I could fall back on that.

Edit:

I suppose that I am not actually using JSON. I output them as variables to a Javascript file so that I can include them as JSON objects in another Javascript file. Looks like I'll either need to use YAML or just do some sort of string editing and abandon strict JSON encoding.


The format you want to write is not JSON. The format is very specific of what can be a value in a json object, and it doesn't have the concept of a javascript variable. What you're trying to write is javascript, not JSON - and that's not the same.

So you can eiter simply try to remove the quotes around your special variables, or write your own serializer.


How about sending the first jsonStyle JSON using json.dumps ? Change the variable jsonStylePyObject and it gets reflected in all further JSONs. Something like the below:

jsonStylePyObject = {'color': '#004070',
    'weight': 2,
    'opacity': 0.9}
myFile.write(json.dumps(jsonStyle))

#then use it normally
js = {'type': 'Feature',
      'properties':
          {'style': jsonStylePyObj},
      'geometry': geomJSON}
myFile.write(json.dumps(jsonStr))

Or you could use string substitution. This is actually bad and not really suggested. You can have an unique string in the style field something like `"MY_UNIQUE_STRING$#!@#" and do a string replace on it. Something like:

jsonStr = json.dumps({'type': 'Feature',
          'properties':
              {'style': "MY_UNIQUE_STRING$#!@#"},
          'geometry': geomJSON})
quotes_char = "'"
jsonStr = jsonStr.replace("%sMY_UNIQUE_STRING$#!@#%s"%(quotes_char, quotes_char), "jsonStyle")
myFile.write(jsonStr) 
链接地址: http://www.djcxy.com/p/47142.html

上一篇: 解码python中的json字符串

下一篇: 在Python JSON中对Javascript变量名进行编码