Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I JSON.parse a string with HTML tag?

I have a string like this:

{"Restriction":"<wbr><a href=\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\" 
target=\"_blank\"><span style=\"color: rgb(0, 0, 205);\">more info</span></a></wbr>"}

but I can't parse it with JSON.parse. My code looks like this:

var s = '{"Restriction":"<wbr><a href=\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\" target=\"_blank\"><span style=\"color: rgb(0, 0, 205);\">more info</span></a></wbr>"}';
var obj = JSON.parse(s);

and I got the error:

Uncaught SyntaxError: Unexpected token.

My guess is 「\"」 made something wrong, but I can't change the string because I got it from a call to a remote API. Here's my code:

// We need this to build our post string
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');

function PostCode(codestring) {

  // An object of options to indicate where to post to
  var post_options = {
      host: 'api.domain',
      port: '80',
      path: '/webservice/service.asmx/method?key=123456',
      method: 'GET',
      headers: {
          'Content-Type': 'text/plain'
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        var x = {};
          console.log('Response down');
          x = JSON.parse(chunk);
      });
  });

  post_req.end();

}
PostCode();
like image 473
Marsen Lin Avatar asked Mar 15 '23 05:03

Marsen Lin


1 Answers

You can't to parse the chunk of data, you need to load all.

  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      var json = '';
      res.on('data', function (chunk) {
        // Why this arg called chunk? That's not all data yet
        json += chunk;
      });
      res.on('end', function(){
         // Here we get it all
         console.log(JSON.parse(json));
      });

  });
like image 83
vp_arth Avatar answered Mar 26 '23 09:03

vp_arth