0

I'm having trouble appending an array to a multi-dimensional JSON array using python whilst giving it the correct desired formatting.

I'm currently reading lines from a text file and appending them to a python array:

with open("./strings/strings.txt", "r") as stringsFile:
    for line in stringsFile:
        strings_array.append(line.strip())

strings.txt:

someotherstring
someotherstring2

Then I open a JS file, get the existing multi-dimensional array and parse it to JSON so I can append my strings_array to it:

with open("./test/strings.js", "r") as stringsJS:
    js = stringsJS.read()
    js = js.strip("module.exports = ")
    test_json = json.loads(js)
    test_json.insert(0, [strings_array[0], [strings_array[1]])
    print(json.dumps(test_json, indent=4, sort_keys=True))

strings.js:

module.exports = [
    ["somestring", "somestring"]
]

When I print the json.dumps the output looks like:

[
    [
        "someotherstring", 
        "someotherstring2"
    ], 
    [
        "somestring", 
        "somestring"
    ]
]

But the desired output is:

[
    ["somestring", "somestring"],
    ["someotherstring", "someotherstring2"]
]

Is there anyway I can achieve the desired output?

martineau
  • 119,623
  • 25
  • 170
  • 301
decprog
  • 167
  • 2
  • 5
  • 22

0 Answers0