如何从json数据中的标记列表中拆分和提取每个标记名?

时间:2013-11-07 04:09:24

标签: python-2.7 django-models

      "tags" : "['x', 'y', 'z']"

我想提取每个元素并将每个元素添加到像

这样的标记表中
       tag1 = x
       tag2 = y 
       tag3 = z 

我需要将标签表中的每个标签存储在事件的不同行中。

     table: Event
       id, title, ...

     table: Tag
       Tagid, eventid, tagname

每个活动的标签都有所不同。

3 个答案:

答案 0 :(得分:0)

>>> t = {"tags" : "['x', 'y', 'z']"}
>>> import ast
>>> ast.literal_eval(t['tags'])
['x', 'y', 'z']

现在它是list

答案 1 :(得分:0)

或没有eval:

t = {"tags" : "['x', 'y', 'z']"}
tags = [el.replace("'","").strip() for el in t['tags'][1:-1].split(',')]

# Basic string splitting:
tags = t['tags'].split(',')

# To replace a character in a string, like "z"
"a123".replace("a", "b") => "b123

# To strip whitespace:
"  Wow  ".strip() => "Wow"

# Then, a list comprehension to loop through elements of an array and put them in new array:
x = [1, 2, 3]
y = [i+1 for i in x]  =>  [2, 3, 4]

# All together, this becomes
tags = [el.replace("'","").strip() for el in t['tags'][1:-1].split(',')]

有人说eval是邪恶的,因为它受到代码注入,因此可能无法预测。但只要你相信输入,就应该没问题。使用ast.literal_eval要好于eval,因为它只评估基本类型,因此您不必担心代码注入。

答案 2 :(得分:0)

来自Ignacio Vazquez-Abrams给出的答案我可以将其更改为如下列表:

     tags = ast.literal_eval(tags)  #converted to the list

     ##Stored the tags with event_id in the tags table. 
     eventobj = Event.objects.get(pk=1)
     for i in range(len(tags)):
        tagsobj = Tags.objects.create(name = tags[i], event_id = eventobj.pk)
     tagsobj.save()