簡體   English   中英

從HTML提取JSON <script> tag with JavaScript

[英]Extract JSON from HTML <script> tag with JavaScript

網頁的html樹中的script標簽中包含JSON。 我需要提取該JSON對象並將其作為JSON對象進行操作。 請提出建議,我該如何實現。 我正在嘗試以這種方式:

var url = 'https://indooroopillyshopping.com.au/stores/'
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
console.log("sending request to ", url);
//WAIT
xhr.send();
console.log("receive respond from ", url);

var data = xhr.responseText;
var json = data.match(/\[{"id":"836","title":"Acutherapy".*/g); //I need an object window.STORES = [{}]
var parsedJson = JSON.parse(stringJson);//catch an error

我也嘗試這樣做:

var json = data.match(/{"id":"836","title":"Acutherapy".*/g);
var newjson = json[0].substring(0, json[0].length-2);//remove space and square bracket at the end
var stringJson = JSON.stringify(newjson);
var parsedJson = JSON.parse(stringJson)
console.log(parsedJson[0].id)//I cannot access JSON with dot notation as it acts like a string (object but not [Object object])

我需要做的就是將json字符串轉換為json對象,以訪問其鍵和值。

幸運的是,我自己找到了解決方案。 我無法解析提取的json,因為它是';' 在字符串的末尾,作為提取為'[{}];'的字符串。 我應該看起來像是-'[{}]'。 也許這對某人有用

var data = xhr.responseText;
var json = data.match(/\[{"id":"836","title":"Acutherapy".*/g);

var newjson = json[0].substring(0, json[0].length-1);
var parsedJson = JSON.parse(newjson)
console.log(parsedJson[1].id); //668

使用JSON.parse() (大多數瀏覽器支持),就像下面的示例一樣簡單:

var json = '{"key1":1,"key2":2}',
var parsedJson = JSON.parse(json);   
console.log(parsedJson.key1);

暫無
暫無

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

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