-1

I am writing a parser to grab data from GitHub api, and I would like to output the file into the following .js format:

//Ideal output
var LIST_DATA = [
{
    "name": "Python",
    "type": "category"
}]

Though I am having trouble writing into output.js file with the variable var LIST_DATA, no matter what I do with the string, the end result shows as "var LIST_DATA"

For example:

//Current Output
"var LIST_DATA = "[
{
    "name": "Python",
    "type": "category"
}]

My Python script:

var = "var LIST_DATA = "
with open('list_data.js', 'w') as outfile:
     outfile.write(json.dumps(var, sort_keys = True))

I also tried using strip method according to this StackOverflow answer and got the same result

var = "var LIST_DATA = "
with open('list_data.js', 'w') as outfile:
     outfile.write(json.dumps(var.strip('"'), sort_keys = True))

I am assuming, whenever I am dumping the text into the js file, the string gets passed in along with the double quote... Is there a way around this?

Thanks.

Yu Zhou
  • 3
  • 3
  • Don't use `json.dumps` when you write the `var LIST_DATA = `, it is interpreted as a JSON value and so gets wrapped in quotes. – Will Richardson Apr 16 '18 at 20:13
  • 1
    `var LIST_DATA = [...` is not valid JSON, so `json.dumps` will never output it. What you need is to `outfile.write('var LIST_DATA = '); json.dump(whatever_proper_data, outfile, indent=1)`. – 9000 Apr 16 '18 at 20:14
  • 1
    Thanks so much guys, wow... Of course, now it makes sense: json = quote.... – Yu Zhou Apr 16 '18 at 20:20

2 Answers2

0

Try

var = '''var LIST_DATA = [
{
    name: "Python",
    type: "category"
}]'''
with open("list_data.js", "w") as f:
    f.write(var)

The json library is not what you are looking for here.

And also, dictionaries in Javascript do not require quoted keys unless there are spaces in the key.

Output: Output

GalacticRaph
  • 872
  • 8
  • 11
0

If you pass a string to json.dumps it will always be quoted. The first part (the name of the variable) is not JSON - so you want to just write it verbatim, and then write the object using json.dumps:

var = "var LIST_DATA = "
my_dict = [
  {
    "name": "Python",
    "type": "category"
  }
]
with open('list_data.js', 'w') as outfile:
    outfile.write(var)
    # Write the JSON value here
    outfile.write(json.dumps(my_dict))
Will Richardson
  • 7,780
  • 7
  • 42
  • 56