简体   繁体   中英

How can I most easily parse this HTTP response into JSON to then access responseText fields?

I'm trying to parse the plaintext that's returned from this URL -- https://www.cloudflare.com/cdn-cgi/trace -- in order to read the IP address value. This is the code snippet I'm using for the request:

 ipAddress = $.get('https://www.cloudflare.com/cdn-cgi/trace', function(data) { return data; });

When logged in browser console, the response looks like the following:

在此处输入图像描述

I've tried using JSON.stringify() , accessing responseText using ['responseText'] , as well as .responseText .. but no luck.

How can this response be parsed so that I can most easily access the ip value from within responseText ?

$.get("https://www.cloudflare.com/cdn-cgi/trace", function(data) {
  const [ ,ip ] = data.match(new RegExp("ip=" + "(.*)" + "\n"));
  console.log(ip);
});

Outputs

"2a01:cb18:362:2200:e90e:fb09:8445:6302"

You can either parse on carriage return or simply look for the ip= in the string or use a regex search it.

If you look at ipAddress.reponseText it's a carriage return delimited string. so

var myip=ipAddress.responseText.split('\n');
console.log(myip[2]); 'the text ip=192.168.1.10  for example if it's always in the same position.  

If it's not in the same position then look through the array to find it.

its return document as response, so i'm not pretty clear about JSON, here some way

 const ipAddress = $.get('https://www.cloudflare.com/cdn-cgi/trace', function (data) { const arr = data.split("\n") const ip = arr.filter(v => v.includes("ip="))[0] console.log(ip.split("=")[1]) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM