JSON.parse:JSON数据的第1行第1列的意外字符

时间:2015-10-30 06:05:43

标签: 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 #

1 个答案:

答案 0 :(得分:3)

您不必使用response = JSON.parse(response);。您的回复已经是一个对象。你不需要再把它解析为对象。