2016-05-06 2 views
0

У меня есть сценарий Grease Monkey, который в основном собирает информацию из игры и отправляет ее на мой сервер, чтобы отслеживать прогресс для нашей команды. Это связано с несколькими запросами Ajax между моим GM-скриптом и игрой, а затем отправкой одного большого дампа на сервер. Во время сбора данных из игры кажется, что один или несколько результатов запроса неверно отформатированы JSON. Я напечатал его на консоли, и это, кажется, строка, а не объект. Я пробовал быстро JSON.parse(JSON.stringify(r)), но это вызывает ошибку unexpected end of data. После некоторых исследований я придумал функцию ниже, чтобы обрабатывать ответ Ajax, но зарегистрированный «объект» по-прежнему представляется строкой и все еще приводит к сбою остальной части сценария.проблема с парсером json с стороннего сервера

function(r){ 
    if(typeof r === 'object'){ 
     result = r; 
    }else if(typeof r === 'string'){ 
     r.trim(); 
     if(r.charAt(0) == '"'){ 
      fNQ = r.indexOf('"') + 1; 
      lNQ = r.lastIndexOf('"'); 
      r = r.substring(fNQ, lNQ); 
      r = r.trim(); 
     } 
     uW.console.log(r); 
     result = r; 
    } 
    if(!result){ 
     result = r; 
    } 
} 

Как я могу гарантировать, что Ajax ответ 3-й партии правильно отформатирован в формат JSON для использования остальной части сценария?

EDIT - Ниже приводится ответ, который, кажется, чтобы вызвать мои ошибки:

" 







{"ok":true,"currentPage":1,"noOfPages":119,"otherAlliances":[{"allianceId":2090,"description":"Everyone has a Voice. Everyone is Equal. No Wild attacks other than that, treat other members with respect in chat, be active, nothing else but having fun your way!!!","membersCount":"77","name":"Rebels Forever","founderUserId":"18985927","might":"4003992566340","glory":"4439079","ranking":1,"hostUserId":"19002651","host":"Greywolf","hostGenderAndName":"Lord Greywolf","founderName":"GreywolfII","founderGenderAndName":"Lord GreywolfII"},{"allianceId":4428,"description":"When the world isnt what you thought. Things are not what they seemed. Phuck it take two of these mix with Alcohol and feel better in the morning.","membersCount":"92","name":"Phuckitol","founderUserId":"450033","might":"3070673000317","glory":"808848","ranking":2,"hostUserId":"450033","host":"Steelman","hostGenderAndName":"Lord Steelman","founderName":"Steelman","founderGenderAndName":"Lord Steelman"},{"allianceId":3253,"description":"Play as you like with the backing of your family. We fight as one and defend as one. Gem prizes will be handed out. Important to have fun and enjoy the game. Zilla","membersCount":"46","name":"Burn In Ashes","founderUserId":"3359434","might":"2596318711111","glory":"1914207","ranking":3,"hostUserId":"12858988","host":"gaz","hostGenderAndName":"Lord gaz","founderName":"Real'Savage","founderGenderAndName":"Lord Real'Savage"},{"allianceId":3262,"description":"Come join us and work as a team to fight and win :)","membersCount":"86","name":"Rise of Legends","founderUserId":"15149877","might":"2379467424780","glory":"2237089","ranking":4,"hostUserId":"15149877","host":"BRETT","hostGenderAndName":"Lord BRETT","founderName":"BRETT","founderGenderAndName":"Lord BRETT"},{"allianceId":3215,"description":":) zero drama tolerance, a place to fight and have fun. Is suppose to be a game after all","membersCount":"67","name":"trouble makers","founderUserId":"1887356","might":"2348999870474","glory":"2428809","ranking":5,"hostUserId":"11564038","host":"Dem0","hostGenderAndName":"Lord Dem0","founderName":"'Echo'","founderGenderAndName":"Lady 'Echo'"},{"allianceId":4924,"description":"","membersCount":"52","name":"WDW","founderUserId":"11577054","might":"2271325408341","glory":"2996503","ranking":6,"hostUserId":"11577054","host":"Nordic","hostGenderAndName":"Lord Nordic","founderName":"Nordic","founderGenderAndName":"Lord Nordic"},{"allianceId":2792,"description":"Name says it all :)","membersCount":"80","name":"Wicked MisFits","founderUserId":"18718109","might":"1984311364223","glory":"2303516","ranking":7,"hostUserId":"18718109","host":"Of_Sin","hostGenderAndName":"Lord Of_Sin","founderName":"Of_Sin","founderGenderAndName":"Lord Of_Sin"},{"allianceId":3881,"description":"","membersCount":"55","name":"LA MEUTE","founderUserId":"14440588","might":"1807184812409","glory":"862782","ranking":8,"hostUserId":"15336296","host":"lepoison","hostGenderAndName":"Lord lepoison","founderName":"LouvePoison","founderGenderAndName":"Lady LouvePoison"},{"allianceId":3273,"description":"Italians do it better.","membersCount":"80","name":"MADE in ITALY","founderUserId":"18656989","might":"1799034994799","glory":"718309","ranking":9,"hostUserId":"19009341","host":"Super_Bicio","hostGenderAndName":"Lord Super_Bicio","founderName":"Leonida","founderGenderAndName":"Lord Leonida"},{"allianceId":5283,"description":"Fight and have fun!","membersCount":"26","name":"War Crimes","founderUserId":"15105685","might":"1599775320583","glory":"6732908","ranking":10,"hostUserId":"15105685","host":"Hillz","hostGenderAndName":"Lady Hillz","founderName":"Hillz","founderGenderAndName":"Lady Hillz"}]}" 
+1

Можете ли вы опубликовать пример ответа json? – yelsayed

+0

@YasserElsayed обновил вопрос с ответом json в вопросе – chaoskreator

ответ

1

Вы пытаетесь разобрать строку после ее повторного выделения. Удалите это дополнительно JSON.stringify, иначе вы получите дополнительные кавычки.

+0

Вы правы, что это препятствовало скрипту. При дальнейшей работе скрипта с отладкой теперь у меня есть на месте, я обнаружил, что один из последних ответов, что также вызывает сценарий аварии был на самом деле немного кода посылается сервером: '» (функция() {return eval (unescape ("% 76% 61% 72% 20% 73% 20% 3% 20% 6е% 65% 77% 20% 44% 61% 74% 65% 28% 29% 3b % 20% 3б% 20% 64% 6f% 20% 7b% 20% 3б% 20% 7d% 20% 77% 68% 69% 6c% 65% 28% 28% 6e% 65% 77% 20% 44% 61 % 74% 65% 28% 29% 29% 20% 2д% 20% 73% 20% 3с% 20% 32% 30% 31% 38% 29% 3b "));})()" ' – chaoskreator

+0

@chaoskreator, что по некоторым причинам, код создает цикл за 2018 миллисекунд. Кажется немного странным, что он скрыт за «unescape» и «eval». – Jaketr00

+0

@ Jaketr00 Да, я не скрыл все и увидел странный счет и задавался вопросом, для чего это может быть. Единственное, о чем я могу думать, это разобрать запросы на сервер. – chaoskreator

0

отлично работает для меня строк шаблона.

var response = `{"ok":true,"currentPage":1,"noOfPages":119,"otherAlliances":[{"allianceId":2090,"description":"Everyone has a Voice. Everyone is Equal. No Wild attacks other than that, treat other members with respect in chat, be active, nothing else but having fun your way!!!","membersCount":"77","name":"Rebels Forever","founderUserId":"18985927","might":"4003992566340","glory":"4439079","ranking":1,"hostUserId":"19002651","host":"Greywolf","hostGenderAndName":"Lord Greywolf","founderName":"GreywolfII","founderGenderAndName":"Lord GreywolfII"},{"allianceId":4428,"description":"When the world isnt what you thought. Things are not what they seemed. Phuck it take two of these mix with Alcohol and feel better in the morning.","membersCount":"92","name":"Phuckitol","founderUserId":"450033","might":"3070673000317","glory":"808848","ranking":2,"hostUserId":"450033","host":"Steelman","hostGenderAndName":"Lord Steelman","founderName":"Steelman","founderGenderAndName":"Lord Steelman"},{"allianceId":3253,"description":"Play as you like with the backing of your family. We fight as one and defend as one. Gem prizes will be handed out. Important to have fun and enjoy the game. Zilla","membersCount":"46","name":"Burn In Ashes","founderUserId":"3359434","might":"2596318711111","glory":"1914207","ranking":3,"hostUserId":"12858988","host":"gaz","hostGenderAndName":"Lord gaz","founderName":"Real'Savage","founderGenderAndName":"Lord Real'Savage"},{"allianceId":3262,"description":"Come join us and work as a team to fight and win :)","membersCount":"86","name":"Rise of Legends","founderUserId":"15149877","might":"2379467424780","glory":"2237089","ranking":4,"hostUserId":"15149877","host":"BRETT","hostGenderAndName":"Lord BRETT","founderName":"BRETT","founderGenderAndName":"Lord BRETT"},{"allianceId":3215,"description":":) zero drama tolerance, a place to fight and have fun. Is suppose to be a game after all","membersCount":"67","name":"trouble makers","founderUserId":"1887356","might":"2348999870474","glory":"2428809","ranking":5,"hostUserId":"11564038","host":"Dem0","hostGenderAndName":"Lord Dem0","founderName":"'Echo'","founderGenderAndName":"Lady 'Echo'"},{"allianceId":4924,"description":"","membersCount":"52","name":"WDW","founderUserId":"11577054","might":"2271325408341","glory":"2996503","ranking":6,"hostUserId":"11577054","host":"Nordic","hostGenderAndName":"Lord Nordic","founderName":"Nordic","founderGenderAndName":"Lord Nordic"},{"allianceId":2792,"description":"Name says it all :)","membersCount":"80","name":"Wicked MisFits","founderUserId":"18718109","might":"1984311364223","glory":"2303516","ranking":7,"hostUserId":"18718109","host":"Of_Sin","hostGenderAndName":"Lord Of_Sin","founderName":"Of_Sin","founderGenderAndName":"Lord Of_Sin"},{"allianceId":3881,"description":"","membersCount":"55","name":"LA MEUTE","founderUserId":"14440588","might":"1807184812409","glory":"862782","ranking":8,"hostUserId":"15336296","host":"lepoison","hostGenderAndName":"Lord lepoison","founderName":"LouvePoison","founderGenderAndName":"Lady LouvePoison"},{"allianceId":3273,"description":"Italians do it better.","membersCount":"80","name":"MADE in ITALY","founderUserId":"18656989","might":"1799034994799","glory":"718309","ranking":9,"hostUserId":"19009341","host":"Super_Bicio","hostGenderAndName":"Lord Super_Bicio","founderName":"Leonida","founderGenderAndName":"Lord Leonida"},{"allianceId":5283,"description":"Fight and have fun!","membersCount":"26","name":"War Crimes","founderUserId":"15105685","might":"1599775320583","glory":"6732908","ranking":10,"hostUserId":"15105685","host":"Hillz","hostGenderAndName":"Lady Hillz","founderName":"Hillz","founderGenderAndName":"Lady Hillz"}]}` 

var data = JSON.parse(response) 
console.log(data) 
Смежные вопросы