I'd like to change the one-dimensional list to json form.

Asked 1 years ago, Updated 1 years ago, 70 views

a.py

dd=['norm9_ab1', 'dataset-hdf', 'audio', 'csvfile', 'saveHDF', 'backend_test', 'keras-adversarial', 'pathconnect']

filelist=[]

i=1
while i < len(ddd):
    filelist.append('\"'+str(i)+'\":'+'\"'+ddd[i]+'\"')
    i=i+1

print(filelist)

I'm going to make a one-dimensional array called ddd into a json shape. I'm changing it completely manually, is there a library that can change it easily? I looked it up. I don't know if I'm not good at searching. It's not coming out well.

Results

['"1":"dataset-hdf"', '"2":"audio"', '"3":"csvfile"', '"4":"saveHDF"', '"5":"backend_test"', '"6":"keras-adversarial"', '"7":"pathconnect"']

json python list

2022-09-22 20:04

2 Answers

The json module is provided among the Python primary modules.

By the way, the result you want is in the key:value, right?

Please refer to the example below.

import json

ddd = ['norm9_ab1', 'dataset-hdf', 'audio', 'csvfile', 'saveHDF', 'backend_test', 'keras-adversarial', 'pathconnect']
M = dict(zip(range(1, len(ddd) + 1), ddd))
json.dumps(M)


'{"1": "norm9_ab1", "2": "dataset-hdf", "3": "audio", "4": "csvfile", "5": "saveHDF", "6": "backend_test", "7": "keras-adversarial", "8": "pathconnect"}'


2022-09-22 20:04

Go for it

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

func main() {
    ddd := []string{"norm9_ab1", "dataset-hdf", "audio", "csvfile", "saveHDF", "backend_test", "keras-adversarial", "pathconnect"}
    M := make(map[string]string)
    for k, v := range ddd {
        M[strconv.Itoa(k+1)] = v
    }
    jsonStr, _ := json.Marshal(M)
    fmt.Println(string(jsonStr))
}

{"1":"norm9_ab1","2":"dataset-hdf","3":"audio","4":"csvfile","5":"saveHDF","6":"backend_test","7":"keras-adversarial","8":"pathconnect"}


2022-09-22 20:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.