Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - Python dictionary/json duplicate keys

Before asking I would like to say I'm not experienced and still learning.

I need to be nested draggable tree and found this he-he-tree for vuejs, which would work perfectly for my needs: https://he-tree-vue.phphe.com/

I have a Python/Flask API that would provide the data to feed the tree in vue.

The problem is that he-he-tree works with js array that looks like this:

treeData: [{text: 'node 1'}, {text: 'node 2', children: [{text: 'node 2-1'}]}, {text: 'node 3'}, {text: 'node 4'}, {text: 'node 5'}, {text: 'node 6'}]

but Python doesn't allow dictionaries to have duplicate keys.

Pretty much, this is how I'm trying to publish the data in Flask:

def rawdata():
    data = {
        "text": "node1",
        "text": "node2",
        "text": "node3",
    }
    return make_response(jsonify(data), 200)

though as python dictionaries do not allow duplicate keys, it's throwing only the last one.

I found a few discussions on similar questions like this one: Make a dictionary with duplicate keys in Python

Though that doesn't really help in my case...

Any workaround that would help me here?

Thanks!

RESOLVED

python_user commented on this question and then deleted his comment, though that solved my problem. I'm still too newbie. He advised that in the JS code I have list of dicts, where in my python I have a simple dict, which is pretty much the problem. Converting my code like that:

def rawdata():

    data = [
        {"text" : "node1"},
        {"text" : "node2"},
        {"text" : "node3"}
        ]
    
    return make_response(jsonify(data), 200)

works as expected.

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create the structure like this:

data = [
    {"text": "node1"},
    {"text": "node1"},
    {"text": "node1"}
]

Your JavaScript does not expect duplicate keys, but separate objects following the same key structure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...