javascript - JSON.解析 : unexpected character at line 1 column 1 of the JSON data

标签 javascript jquery python json

这是我的 javascript 代码,它调用 python 文件并在结果中接收 json 响应:

<script>
                $.ajax({
                      url: "read_excel.py",
                      type: "GET",
                      // data: data,
                      success: function(response){
                        $("#loader").addClass("hide");
                        console.log(response);
                        response = JSON.parse(response);
    FusionCharts.ready(function () {
    var topProductsChart = new FusionCharts({
        type: 'multilevelpie',
        renderAt: 'chart-container',
        id : "myChart",
        width: '500',
        height: '500',
        dataFormat: 'json',
        dataSource: {
            "chart": {
                "caption": "Word Frequency",
                "subCaption": "Location Wise",
                "captionFontSize": "14",
                "subcaptionFontSize": "14",
                "baseFontColor" : "#333333",
                "baseFont" : "Helvetica Neue,Arial",   
                "basefontsize": "9",
                "subcaptionFontBold": "0",
                "bgColor" : "#ffffff",
                "canvasBgColor" : "#ffffff",
                "showBorder" : "0",
                "showShadow" : "0",
                "showCanvasBorder": "0",
                "pieFillAlpha": "60",
                "pieBorderThickness": "2",
                "hoverFillColor": "#cccccc",
                "pieBorderColor": "#ffffff",
                "useHoverColor": "1",
                "showValuesInTooltip": "1",
                "showPercentInTooltip": "0",
                "numberPrefix": "$",
                "plotTooltext": "$label, $$valueK, $percentValue"
            },
            "category": [
                {
                    "label": "Word Frequency By Location",
                    "color": "#ffffff",
                    "value": "150",
                    "category": response
                }
            ]
        }
    });

    topProductsChart.render();
});
                      },
                      error: function(html){
                        console.log("error");
                      }
                    });
    </script>

python 脚本:

#!/usr/bin/python
import re
import csv
import json
import cgi
import random
import pprint 
import traceback
from collections import Counter
from nltk.corpus import stopwords

class  ReadCSV(object):
    """docstring for  ReadExcel"""
    def __init__(self):
        self.all_location = []
        self.location_wise_tags = []
        self.frmt_location_tags = []
        self.stop_words = stopwords.words('english')

    def hexColor(self):
        r = lambda: random.randint(0,255)
        return '#%02X%02X%02X' % (r(),r(),r())

    def wd_freq(self, tags):
        dict_word_freq = Counter(tags)
        dict_word_freq = [{ k: v } for k, v in dict_word_freq.iteritems() if k not in self.stop_words]
        return dict_word_freq

    def format_json(self, location, dict_word_freq):
        color = self.hexColor()
        self.frmt_location_tags.append( {"label" : location, "color": color, "value": str(len(dict_word_freq)), "category" : [] } )
        for d_w in dict_word_freq:
            self.frmt_location_tags[-1]["category"].append( {"label": d_w.keys()[0], "color": color, "value": str(d_w.values()[0])} )
        # pprint.pprint( self.frmt_location_tags )

    def  readSheet(self):
        with open('all.csv', 'rb') as csvfile:
            spamreader = csv.reader(csvfile.read().splitlines())
            i = 0
            for row in spamreader:
                try:
                    i += 1
                    text = row[8]
                    location = row[10]
                    n_location = re.findall( re.compile(ur'(\w+=)') , location)
                    if n_location:
                        n_location = n_location[0][0: len(n_location[0]) - 1]
                        location = n_location
                    # print text, "---" , location
                    tags = self.findTags(text)
                    if location not in self.all_location:
                        if self.all_location:
                            dict_word_freq = self.wd_freq( sum(self.location_wise_tags, []) )
                            self.format_json( self.all_location[-1], dict_word_freq )
                            self.location_wise_tags = []
                        self.all_location.append(location)
                        self.location_wise_tags.append(tags)
                    else:
                        self.location_wise_tags.append(tags)
                    if i > 20:
                        break
                except Exception:
                    # import traceback
                    # print traceback.format_exc()
                    # print location
                    pass

    def findTags(self, text):
        pattern = re.compile(ur'(#\w+)|(@\w+)')
        return [filter(None, x)[0] for x in re.findall(pattern, text)]

    def run(self):
        self.readSheet()
        return self.frmt_location_tags

if __name__ == '__main__':

    try:
        #print "\n"
        result = ReadCSV().run()
        json_string = json.dumps( result )
        print json_string
    except Exception:
        import traceback
        print traceback.format_exc()

看起来像:

[
  {"color": "#448DB2", "value": "1", "label": "#buddiez"}, 
  {"color": "#448DB2", "value": "2", "label": "#instaedit"}, 
  {"color": "#448DB2", "value": "1", "label": "#Carefree"}, 
  {"color": "#448DB2", "value": "1", "label": "#Ican"}, 
  {"color": "#448DB2", "value": "1", "label": "#streetlight"}
], "value": "3405", "label": "Ahmedabad"}]

当我运行我的 html 文件时,它会在控制台中显示此消息:

not well-formed read_excel.py:1:2
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data graphs.html:27:36

有什么地方出错的建议吗?

更新:

现在按照 Anup 的回答消除了错误。但是收到的 json 似乎格式不正确,对此有什么建议吗?

现在我得到这个错误:

Uncaught SyntaxError: Unexpected token #

最佳答案

您不必使用 response = JSON.parse(response);。您的回应已经是一个对象。您无需再次将其解析为对象。

关于javascript - JSON.解析 : unexpected character at line 1 column 1 of the JSON data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429671/

相关文章:

javascript - 单击同一提交按钮以 react-redux 形式更新状态和 Prop

javascript - 当有2个 `catch` es时抛出正确的消息

jquery - 包含位置 : absolute elements inside of a div, 以便可以在其前后插入position:relative div

javascript - 检测拖动对象下方的多个元素? Javascript/Jquery

python - 如何将 quotient_graph 结果写入文件

javascript - 如何使用jquery从两个输入中获取值

javascript - 使用用户当前时间 JavaScript 更改 CSS

jquery - 在不使用php的情况下使用JQuery访问Mysql

python - Django 和 Folium 集成

python - 如何根据 Python Pandas 中 DataFrame 中其他 2 列中的值删除一列中的重复项?