在Javascript,Django中进行数组转换的对象

时间:2018-04-18 07:04:28

标签: javascript django

我在Django中使用render_to_response从Views向Javascript发送一个列表。但在Javascript中,我将输入作为字符串,我无法将其转换为数组。

我需要拼接数组以提取3个不同的属性。

  1. data_positive
  2. data_negative
  3. data_neutral
  4. views.py中的

    sentiment1 变量是我面临错误的属性。

    def allexist(request):
    response = {}
    responseList = []
    sentimentlist = []
    dt = {}
    fetchedhash = []
    senti_vals = []
    positive_list = []
    negative_list = []
    neutral_list = []
    positive_vals = []
    negative_vals = []
    neutral_vals = []
    sentiments = {}
    d = Registered.objects.filter(id=userid).values('projectid', 'pname')
    
    for x in d:
        date1 = Registered.objects.filter(projectid=x["projectid"]).values('startdate', 'enddate')
        for dt in date1:
            end = dt["startdate"]
            startd = dt["startdate"].date()
            startt = dt["startdate"].time()
            endd = dt["enddate"].date()
            endt = dt["enddate"].time()
    
            final = datetime.combine(startd, startt)
            final2 = final.replace(minute=00, second=00)
            finale = datetime.combine(endd, endt)
            finale2 = finale.replace(minute=00, second=00)
    
            word_list=[]
            e = Hashtagmodel.objects.filter(projectid=x["projectid"]).values('hashtaglist')
    
            for hashes in e:
                d = Tweetsmodel.objects.filter(UserID=userid, isoDate__range=(final2, finale2),
                                               TweetText__icontains=hashes["hashtaglist"]).values('isoDate').annotate(
                    total=Count('TweetText')).order_by('isoDate')
    
                w = Tweetsmodel.objects.filter(UserID=userid, isoDate__range=(final2, finale2),
                                               TweetText__icontains=hashes["hashtaglist"]).values("TokeniZedString")
    
                s = Tweetsmodel.objects.filter(UserID=userid, isoDate__range=(final2, finale2),
                                               TweetText__icontains=hashes["hashtaglist"]).values('senti')
    
                # otherCount = 0
                created_at = []
                tweet_count = []
                response = {}
    
                for data in d:
                    created_at.append(data['isoDate'])
                    tweet_count.append(data["total"])
                    # rowData = str(data['isoDate']) + "," + str(data['total'])
    
                response["date"] = created_at
                response["count"] = tweet_count
    
                responseList.append(response)
                for i in w:
                    word_list.append(i["TokeniZedString"])
                concat_string = ','.join(word for word in word_list)
    
                concat_list = concat_string.split(",")
                counts = Counter(concat_list)
                word = []
                pingpong = 0
                for x in counts:
                    pingpong = pingpong + 1
                    if pingpong <= 1000:
                        word.append({"text": x, "size": counts[x]})
                jsonStr = json.dumps(word)
    
                for j in s:
                    senti_vals.append(j["senti"])
                senti_string = ','.join(str(word) for word in senti_vals)
                senti_list = senti_string.split(",")
                counting = Counter(senti_list)
                positive = 0
                negative = 0
                neutral = 0
                for j in counting:
                    if j == '4.0':
                        positive = counting[j]
                        positive_string = "\"positive\":" + str(counting[j])
                    if j == '0.0':
                        negative = counting[j]
                        negative_string = "\"negative\":" + str(counting[j])
                    if j == '1.0':
                        neutral = counting[j]
                        neutral_string = "\"neutral\":" + str(counting[j])
    
                positive_vals = Tweetsmodel.objects.filter(Q(senti="4.0") & Q(TweetText__icontains=hashes["hashtaglist"])).values(
                    'TweetText')
                negative_vals = Tweetsmodel.objects.filter(Q(senti="0.0") & Q(TweetText__icontains=hashes["hashtaglist"])).values(
                    'TweetText')
                neutral_vals = Tweetsmodel.objects.filter(senti="1.0", TweetText__icontains=hashes["hashtaglist"]).values('TweetText')
                positive_string = '-----#$$$%%%%____----'.join(str(word) for word in positive_vals)
                negative_string = '-----#$$$%%%%____----'.join(str(word) for word in negative_vals)
                neutral_string = '-----#$$$%%%%____----'.join(str(word) for word in neutral_vals)
                positive_list = positive_string.split("-----#$$$%%%%____----")
                negative_list = negative_string.split("-----#$$$%%%%____----")
                neutral_list = neutral_string[8:].split("-----#$$$%%%%____----")
                stupid = "\n" + "\n"
                positive_list = positive_list[:15]
                negative_list = negative_list[:15]
                neutral_list = neutral_list[:15]
                positive_list = [x + stupid for x in positive_list]
                negative_list = [x + stupid for x in negative_list]
                neutral_list = [x + stupid for x in neutral_list]
    
                # sentiments = [ {"positive": positive, "negative": negative, "neutral": neutral,"data_positive": positive_list, "data_negative": negative_list,"data_neutral":neutral_list}]
    
                sentiments = [{"positive":positive,"negative":negative,"neutral":neutral}]
                sentiments1=[{"data_positive": positive_list, "data_negative": negative_list,"data_neutral":neutral_list}]
    
                sentimentlist.append(sentiments)
                for alexa in sentimentlist:
                    print("this is response of senti",alexa)
    
        return render_to_response("personal_anshul/allexist.html", {"responseList": responseList,"jsonStr": jsonStr ,"sentimentlist": sentimentlist,"jsonStr1":sentiments1,"e":e})
    return render(request, "personal_anshul/allexist.html")
    

    HTML文件代码段:将sentiment1的值(文本)传递给my_var4

           <script>
    var my_var = "{{ responseList }}";
    var my_var2 = "{{ jsonStr }}";
    var my_var3 = "{{ sentimentlist }}";
    var my_var4 = "{{ jsonStr1 }}";
    var my_var5 = "{{ e }}";
    
    </script>
    

    Javascript片段:

        function decodeHtml(html) {
        var txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    }
    //console.log(my_var4);
    L=decodeHtml(my_var4);
    console.log(typeof(L))
    values = L.split(",/s")
    console.log(values)
    console.log(typeof(values))
    

    L的输出:enter image description here

    以下是使用console.log(my_var4)的my_var4变量的输出

    ***
    
    [{&#39;data_neutral&#39;: [&quot;ext&#39;: &#39;The 5 best deals on #Amazon right now will all make life easier /w60T7iCynr via @enquirer /ly0W1urLs4&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;Reining in Big Data’s Robber\xa0Barons /EL3pu1VS0J #Facebook #Twitter #Amazon /8XiTEG0sPi&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39; /7WJqcDbzNp Promote #Amazon #Affiliate products AUTOMATICALLY with /2cDsaTmPbm #SeoExpert… /nVXBPXUQMm&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @Oldbrookender: Best Selling Action Adventure Series Set in Roman Britain\nFree on Kindle Unlimited\n#iartg #histfic #Rome\n#amazon #bestse…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @omghotels: View from The Shard &amp;amp; River Cruise for Two - Perfect Gift Experience For Two only £89. \n\n /x9lilcNsfF\n\n#Amazon #g…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @Oldbrookender: Best Selling Action Adventure Series Set in Roman Britain\nFree on Kindle Unlimited\n#iartg #histfic #Rome\n#amazon #bestse…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;#Apple, #Google, #Facebook, #Amazon, #Microsoft: Which #Tech Giant Will Fall First? /5hgwF71dDP&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @SusanneSpellman: #The Virus- Book 1  #Amazon /#ITunes /#B&amp;amp;N\n /9hB7mvKFZQ\n\nThe Virus #Book 2 (Coming Soon)\n /Vbcae…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @Dolors111068: LA MANSIÓN DE LOS NAVAS...  de @ja_gonzalez49 Una de las novelas #policíacas más leídas en #Amazon. Ambientada en los año…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @burginvecmo5389: ???????#?????????\n\n??#iTunes???\n10000?×30?\n\n??#Googleplay??? \n10000?×30?\n\n??#Amazon????\n10000?×30?\n\n??????\n\n??????\n?????????…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @mfoulk50: HOLY HUMANITY\nby James Foster\nThought provoking\nperspective after a\nlifetime in ministry\n#amazon\nRT, plz ;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;Simplified Steps To Become An Expert #Amazon Seller @Hounddogdigital /qsmAIJTvKW /5wEJ6CuqKJ&#39;} 
    
    &quot;, &#39;{&#39;TweetText&#39;: &#39;&quot;nothing less than perfection&quot; WHEN I\&#39;M WEAK /OGLpCoexbJ #Amazon #Kindle #kindlebooks #Christianfiction&#39;} 
    
    &#39;, &quot;{&#39;TweetText&#39;: &#39;RT @phonandroid: ?? #FnacDarty et #Google s’allient pour contrer le #HomePod et l’#AmazonEcho #GoogleHome &amp;gt; /zYAjATgVq7 ;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;?[???????!!]GOOD TIMES A COLLECTION OF AMERICAN STANDARDS  #????? #LaserDisc ????#amazon ???!!… /8JMkgjIjCn&#39;} 
    
    &quot;], &#39;data_negative&#39;: [&quot;{&#39;TweetText&#39;: &#39;???????????????????????????????????????? ???? /qxErKTaO8c #books #amazon&#39;} 
    
    &quot;, &#39;{&#39;TweetText&#39;: &quot;4.3 Stars: Women&#39;s Plus Size 711 Skinny  Ankle Jeans for $30. Great Deal for Today! #Monday #Amazon #Deal [… /0YV0NYeXrg&quot;} 
    
    &#39;, &quot;{&#39;TweetText&#39;: &#39;#UK 26% off: Samsung  Level Active Wireless Headphone Black for £59.44. Great Deal for Today! #Monday #Amazon #Deal… /q3gxh6FSu9&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;Philo to Add #Apple TV, Android, and #Amazon Fire TV Support @ Cord Cutters News, LLC .. #?????_??????? /IOgmiDMWBr&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39; /14rCHPGkat\n #Multicultural #Steamy #Romance #Suspense #Contemporary #Free #Book #Kindle #review #amazon /nyOduXxtYT&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @mangahack: ?Android???????????\n?????10?? #Amazon???? 500??????????\n????&amp;amp;RT???????????????? ?5/6(?)23:59??\n\n??????????????????????DL?????…&#39;} 
    
    &quot;, &#39;{&#39;TweetText&#39;: &quot;4.4 Stars: Bcbgmax Azria Women&#39;s  Dara V-neck Dress for $92. Great Deal for Today! #Monday #Amazon #Deal [… /CddVycgV4k&quot;} 
    
    &#39;, &quot;{&#39;TweetText&#39;: &#39;Return to Cedar Hill \n /ECoYAEDBJS  #Free #Book #Kindle #review #amazon #christianfiction #Siblings,… /xpXnczKZpY&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;Return to Cedar Hill \n /XkWAarlRSR  #Free #Book #Kindle #review #amazon #christianfiction #Siblings,… /YptXML70RR&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @corrigenda_es: #DesdeElTragaluz, de @Marie_N_Vianco\n /DGXDhmpzPE    \n#Amazon #thriller #novela\nA veces el lugar más inesper…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;4.7 Stars: Pat  The Patriot Expandable Bangle Bracelet for $32. Great Deal for Today! #Monday #Amazon #Deal [… /lESdb5zcGQ&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @SometimesYouDie: Trump Is Right /g8Z0hLkuUf #USPS #Bezos #Amazon #MAGA @cvpayne&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;??????? (???????) /RxrIgRqVTB #Amazon&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;#starvingartist /IcSYAiuXPI #socialmediamarketing #blog #blogging #asmsg #IARTG #IAN1 #Amazon #AmWriting #firebirdslight&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;????????????? /2UkRy4RLur #Amazon&#39;} 
    
    &quot;], &#39;data_positive&#39;: [&quot;{&#39;TweetText&#39;: &#39;RT @AuthorEllie: The Dead Wake Anthology #Amazon /d5Rv67z5rl  ?????? Are you brave enough? Ten stories to disable you!  #zombies…&#39;} 
    
    &quot;, &#39;{&#39;TweetText&#39;: &quot;RT @W_Angels_Wings: Available on #Amazon ~ With Angel&#39;s Wings\n /t3EG8ScQre\n#AwardWinner #memoir #specialneeds #parenting #Kindle…&quot;} 
    
    &#39;, &#39;{&#39;TweetText&#39;: &quot;#USA Deals: Women&#39;s Printed  Inverted Pleat Dress for $38. Great Deal for Today! #Monday #Amazon #Deal [… /zn1Lco1GwC&quot;} 
    
    &#39;, &quot;{&#39;TweetText&#39;: &#39;#Sondage #ecommerce : Pour vos achats en ligne, quel canal privilégiez vous ?\nLe géant américain #Amazon ? Le franç… /06MCMcBJ23&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;(Actualitté) Chez #Amazon, on pisse dans une bouteille pour éviter des sanctions : Selon.. /Ul8sMwX1T6 /TZ7WVF1HOP&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @kurodorifunny: ????????????2?????? #RT??????\n??10??? #Amazon???? 1000??????\n\n?????2??\n?2000RT?4?\n?3000RT?6?\n?4000RT?8?\n?5000RT?10?\n\n????…&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;Quantum Field Theory /aUHJorhZ1c #Amazon&#39;} 
    
    &quot;, &#39;{&#39;TweetText&#39;: &quot;5.0 Stars: Women&#39;s  Velvet Halter Dress for $129. Great Deal for Today! #Monday #Amazon #Deal [… /K7n05rdqpb&quot;} 
    
    &#39;, &quot;{&#39;TweetText&#39;: &#39;Better With You $25 Blog Tour Giveaway. Enter to win $25 from author Rachel John #Amazon #Paypal /MEOHSnnwRB&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;Dark Energy: Theory and Observations /573ji7vjAy #Amazon&#39;} 
    
    &quot;, &quot;{&#39;TweetText&#39;: &#39;RT @ATAGOofficial: ?\n#Amazon???? 1,000??????!!\n?\n\n1??????????\n? #????????????????????????????? ?\n\n??????\n@ATAGOofficial ????? &amp;amp; ???????RT\n?…&#39;} 
    
    &quot;, &#39;{&#39;TweetText&#39;: &quot;Before we all start thinking of conferring sainthood on #Amazon  because it&#39;s in 45&#39;s crosshairs, read this. And re… /akqRwVmWj0&quot;} 
    
    &#39;, &#39;{&#39;TweetText&#39;: &quot;#USA Deals: Women&#39;s Samantha  Wrap-front Handkerchief Dress for $148. Great Deal for Today! #Monday #Amazon #Deal [… /kDZIVmD9xD&quot;} 
    
    &#39;, &#39;{&#39;TweetText&#39;: &quot;5.0 Stars: Women&#39;s Madalyn  Asymmetrical Faux-wrap Dress for $198. Great Deal for Today! #Monday #Amazon #Deal [… /EnNeHOgVND&quot;} 
    
    &#39;, &#39;{&#39;TweetText&#39;: &quot;4.4 Stars, 609 Reviews: Men&#39;s Big-tall  560 Comfort-fit Jean for $33. Great Deal for Today! #Monday #Amazon #Deal [… /njf82q8PUa&quot;} 
    
    &#39;]}]
    

    如果我拆分它我得到一个对象。但我想要一个阵列。如何在此处转换此数据类型。或者我是否需要遵循任何其他方法?

0 个答案:

没有答案