簡體   English   中英

解析(通過JavaScript)自動創建(通過Python)JSON文件的問題

[英]Issue with parsing (via JavaScript) an automatically created (via Python) JSON file

幾天前,我從一家本地公司接到訂單,要求將其制作為移動應用程序。 設計和UI幾乎已經准備就緒,但是在邏輯上存在一些問題。 這些問題之一是:他們希望其服務列在應用程序主體的下部。

我昨天開始考慮這個問題,並且想到了這個主意:我正在抓取他們的網站,收集所需的數據,並制作了json對象數組,然后使用python將其寫入.json文件。 然后使用javascript,我正在解析此.json文件,並從其中提取必要的部分以顯示在div中。Python成功創建了json文件,但是當JavaScript嘗試對其進行解析時,它不會成功。 我檢查了控制台日志,並SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data (它是我的JSON文件的開頭)顯示了SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我向您介紹我的Python,JS,JSON文件和HTML文件的相關部分。

蟒蛇

from urllib.request import urlopen
from bs4 import BeautifulSoup
import json

def make_json_file():
    titles = []
    captions = []
    sources = []

    serv_url = 'http://www.theclub.az/az/pages/145/150'
    full_page = BeautifulSoup(urlopen(serv_url).read(), "html.parser")

    links = full_page.findAll('a', {'class': 'readmore'})
    for i in range(0, len(links), 2):
        source = links[i]['href']
        sources.append(source)

        title = links[i].findAll('div')[1].string
        titles.append(title)

        caption = 'http://www.theclub.az/' + links[i].findAll('a')[0].img['src']
        captions.append(caption)

    products = [{"title": t, "caption": c, "source": s} for t, c, s in zip(titles, captions, sources)]
    content = json.dumps(products, ensure_ascii=False)

    with open('products.json', 'w') as outfile:
        outfile.write('products = ')
        json.dump(content, outfile)
        outfile.write(';')


make_json_file()

它創建此JSON文件(products.json)

products = "[{\"title\": \"\u0130DMAN ZALI\", \"caption\": \"http://www.theclub.az/bolme-img/8223682236sport.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/194\"}, {\"title\": \"\u00dcZG\u00dc\u00c7\u00dcL\u00dcK HOVUZU\", \"caption\": \"http://www.theclub.az/bolme-img/8394983949hovuz.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/195\"}, {\"title\": \"KARD\u0130O AL\u018fTL\u018fR ZALI\", \"caption\": \"http://www.theclub.az/bolme-img/6862168621card.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/196\"}, {\"title\": \"A\u011eIRL\u0130Q AL\u018fTL\u018fR\u0130 ZALI\", \"caption\": \"http://www.theclub.az/bolme-img/2713327133sport.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/208\"}, {\"title\": \"F\u018fRD\u0130 M\u018f\u015e\u011e\u018fL\u018f\", \"caption\": \"http://www.theclub.az/bolme-img/58989589891.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/197\"}, {\"title\": \"S\u00dcN\u0130 QAYA\", \"caption\": \"http://www.theclub.az/bolme-img/4781247812qaya.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/198\"}, {\"title\": \"SPORT CAFE\", \"caption\": \"http://www.theclub.az/bolme-img/60776607764.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/201\"}, {\"title\": \"THE CLUB SPA\", \"caption\": \"http://www.theclub.az/bolme-img/17042spa.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/216\"}, {\"title\": \"FITNES STUDIYA 1\", \"caption\": \"http://www.theclub.az/bolme-img/34042340421.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/209\"}, {\"title\": \"FITNES STUDIYA 2\", \"caption\": \"http://www.theclub.az/bolme-img/48637486371.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/210\"}, {\"title\": \"TEN\u0130S KORTU\", \"caption\": \"http://www.theclub.az/bolme-img/24234242341.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/203\"}, {\"title\": \"SKVO\u015e KORTLAR\", \"caption\": \"http://www.theclub.az/bolme-img/64949649492.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/204\"}, {\"title\": \"COFFEE SHOP\", \"caption\": \"http://www.theclub.az/bolme-img/55114551141.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/202\"}, {\"title\": \"U\u015eAQ OTA\u011eI\", \"caption\": \"http://www.theclub.az/bolme-img/55813558131.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/206\"}, {\"title\": \"GOLF SIMULYATOR\", \"caption\": \"http://www.theclub.az/bolme-img/3846210.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/199\"}, {\"title\": \"BILYARD OTA\u011eI\", \"caption\": \"http://www.theclub.az/bolme-img/67419674191.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/205\"}, {\"title\": \"SPORT SHOP\", \"caption\": \"http://www.theclub.az/bolme-img/95621956211.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/207\"}, {\"title\": \"SAUNA/BUXAR OTA\u011eI\", \"caption\": \"http://www.theclub.az/bolme-img/2131719.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/211\"}, {\"title\": \"SOLARIUM\", \"caption\": \"http://www.theclub.az/bolme-img/9097520.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/212\"}, {\"title\": \"G\u00d6Z\u018fLL\u0130K SALONU\", \"caption\": \"http://www.theclub.az/bolme-img/4677721.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/213\"}, {\"title\": \"B\u018fRB\u018fR SALONU\", \"caption\": \"http://www.theclub.az/bolme-img/3459922.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/214\"}, {\"title\": \"DZ\u00dcDO D\u018fRSL\u018fR\u0130\", \"caption\": \"http://www.theclub.az/bolme-img/21924judo.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/242\"}]";

HTML和JavaScript

 //s.js window.onload = function() { var prods = document.getElementById("prods"); var products = JSON.parse(products) prods.innerHTML = ''; for (var i = 0; i < products.length; ++i) { var prod = products[i]; prods.innerHTML += '<div class="prd_div"><a class="prd_par" href="' + prod.source + '"><img src="' + prod.caption + '" class="prd" /><p>' + prod.title + '</p></a></div>'; } }; 
 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro"> <link rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="products.json"></script> </head> <body> <div id="prods"></div> <script type="text/javascript" src="s.js"></script> </body> </html> 

我在哪里做錯了? 請幫忙!

JSON文件中不應包含products = part ..而是使用類似{ 'products':[ ... ] }

當您嘗試轉儲文件時可以實現。

    content = {'products':content}
    with open('products.json', 'w') as outfile:
    # outfile.write('products = ')
    json.dumps(content, outfile)
    # outfile.write(';')

這里的問題是,您應該制作一個ajax以獲取JSON。 因此,在您的html中,您應該刪除此行

  <script type="text/javascript" src="products.json"></script>

並且在您的JS文件中,您應該像這樣制作ajax:

function loadAjax() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     console.log(this.responseText) // here you will got the whole json
    }
  };
  xhttp.open("GET", "products.json", true);
  xhttp.send();
}

我不太確定是將其獲取為字符串還是JSON,如果是字符串,則可以通過執行JSON.parse(this.responseText)將其轉換為JSON對象。也正如@vasif所說,JSON文件不應開始時有產品=

s.js聲明的window.onload匿名函數中,

    var products = JSON.parse(products)

聲明一個名為products的局部函數變量,該變量以相同的名稱遮蓋全局變量products並使它不可訪問。 由於局部變量最初未定義,因此代碼等效於

    var products = JSON.parse(undefined);

引發相同的錯誤。 最簡單的解決方案是將用於onload函數中的已解析數據的變量名更改為其他名稱,以防止其影響全局products值。

除此之外,它看起來還不錯-附有鏈接的體育館照片頁面。

請注意,在Python中創建的“ products.json”文件是JSONP文件,而不是JSON文件。

我知道有一個可以接受的答案,但是我不喜歡它。 所以這是我的。

您的products.json文件既不是有效的JSON,也不是無效的Javascript,但是它們的組合都無法使用。

您可以更新python腳本以生成有效的javascript,然后通過名為products.js之類的腳本標簽加載該腳本:

products = [{ name : "value", name: "value"}, {name: "value", name:"value"}];

如果您只希望每個頁面加載一次產品,這將很好地工作。 如果您打算使用更多的ajax,而您希望在不重新加載頁面的情況下更改產品的價值,那么請更改您的python腳本以生成有效的JSON,並將其作為json文件提供:

[{\"title\": \"\u0130DMAN ZALI\", \"caption\": \"http://www.theclub.az/bolme-img/8223682236sport.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/194\"}, {\"title\": \"\u00dcZG\u00dc\u00c7\u00dcL\u00dcK HOVUZU\", \"caption\": \"http://www.theclub.az/bolme-img/8394983949hovuz.jpg\", \"source\": \"http://www.theclub.az/az/pages/150/195\"}]

然后,當您想更改產品文件的值時,可以執行以下操作:

$.get("/path/to/products.json", null, null, "json")
    .done(function(r) {
        products = r;
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM