将JSON String(Prettified)转换回原始字符串(包含所有转义字符)

时间:2016-01-08 20:25:14

标签: javascript json

所以我有一个json字符串,如下所示:

use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 * @UniqueEntity(
 *     fields={"email", "team"},
 *     message="This email already exists in this team."
 * )
 */
class User extends BaseUser
{
    // ...
}

我需要将其转换为原始字符串格式,其中所有特殊字符和符号都替换为unicode或具有转义字符。

MyBundle\Entity\User

我将如何在javascript中执行此操作?
欢迎所有指针。

示例链接 http://api.icflix.com/tv/catalogue/movies?num=1

2 个答案:

答案 0 :(得分:0)

试试这个:

function escapeString(str) {
    var result = '',
        code;

    for (var i = 0; i < str.length; i++) {
        code = str.charCodeAt(i);
        if (code < 32 || code > 126) {
            result += '\\u2' + code;
        } else {
            result += str[i];
        }
    }
    return result;
}

var orig = '{"count":1,"items":[{"rating":"teens","videos":[{"width":1280,"link":"http://192.168.195.86:1081/playback/play/99e2399e-368b","dar_image":1.7777777778,"language":"eng","duration":5166,"type":"main","id":"99e2399e-368b","dar_frame":1.7777777778,"height":720}],"trial":false,"metadata_language":"eng","year":2003,"images":[{"link":"http://192.168.195.86:1081/image/1675610d-e57e.jpg","type":"poster","id":"1675610d-e57e","orientation":"landscape"}],"id":"d0e9d382-e2d4","has_download_policy":true,"title":"Ice Bound","section":"hollywood","crew":[{"role":"director","name":"Roger Spottiswoode"}],"type":"movie","website_url":"http://192.168.195.86:1081/eng/movie/pkdaci6s-ice-bound","description":"Testin\'g «ταБЬℓσ»: 1<{2 & 4+1}>3, now 20% off!@#$%^&*(). Another Testing String ","link":"http://192.168.195.86:1081/movie/d0e9d382-e2d4","slug":"pkdaci6s","categories":[{"link":"http://192.168.195.86:1081/category/ca8a9dce-514d","id":"ca8a9dce-514d","title":"Drama"}],"metadata_direction":"ltr","audio_languages":["eng"],"cast":[{"name":"Susan Sarandon"},{"name":"Aidan Devine"},{"name":"Cynthia Mace"}]}],"remaining":1} ';

result = escapeString(orig);
console.log(result);

结果:

{"count":1,"items":[{"rating":"teens","videos":[{"width":1280,"link":"http://192.168.195.86:1081/playback/play/99e2399e-368b","dar_image":1.7777777778,"language":"eng","duration":5166,"type":"main","id":"99e2399e-368b","dar_frame":1.7777777778,"height":720}],"trial":false,"metadata_language":"eng","year":2003,"images":[{"link":"http://192.168.195.86:1081/image/1675610d-e57e.jpg","type":"poster","id":"1675610d-e57e","orientation":"landscape"}],"id":"d0e9d382-e2d4","has_download_policy":true,"title":"Ice Bound","section":"hollywood","crew":[{"role":"director","name":"Roger Spottiswoode"}],"type":"movie","website_url":"http://192.168.195.86:1081/eng/movie/pkdaci6s-ice-bound","description":"Testin'g \u2171\u2964\u2945\u21041\u21068\u28467\u2963\u2187: 1<{2 & 4+1}>3, now 20% off!@#$%^&*(). Another Testing String ","link":"http://192.168.195.86:1081/movie/d0e9d382-e2d4","slug":"pkdaci6s","categories":[{"link":"http://192.168.195.86:1081/category/ca8a9dce-514d","id":"ca8a9dce-514d","title":"Drama"}],"metadata_direction":"ltr","audio_languages":["eng"],"cast":[{"name":"Susan Sarandon"},{"name":"Aidan Devine"},{"name":"Cynthia Mace"}]}],"remaining":1} 

或者这个:

result = orig.split('').map(function(v) {
    var code = v.charCodeAt(0);
    if (code < 32 || code > 126) {
        return '\\u2' + code;
    } else {
        return v;
    }
}).join('');

console.log(result);

结果相同:

{"count":1,"items":[{"rating":"teens","videos":[{"width":1280,"link":"http://192.168.195.86:1081/playback/play/99e2399e-368b","dar_image":1.7777777778,"language":"eng","duration":5166,"type":"main","id":"99e2399e-368b","dar_frame":1.7777777778,"height":720}],"trial":false,"metadata_language":"eng","year":2003,"images":[{"link":"http://192.168.195.86:1081/image/1675610d-e57e.jpg","type":"poster","id":"1675610d-e57e","orientation":"landscape"}],"id":"d0e9d382-e2d4","has_download_policy":true,"title":"Ice Bound","section":"hollywood","crew":[{"role":"director","name":"Roger Spottiswoode"}],"type":"movie","website_url":"http://192.168.195.86:1081/eng/movie/pkdaci6s-ice-bound","description":"Testin'g \u2171\u2964\u2945\u21041\u21068\u28467\u2963\u2187: 1<{2 & 4+1}>3, now 20% off!@#$%^&*(). Another Testing String ","link":"http://192.168.195.86:1081/movie/d0e9d382-e2d4","slug":"pkdaci6s","categories":[{"link":"http://192.168.195.86:1081/category/ca8a9dce-514d","id":"ca8a9dce-514d","title":"Drama"}],"metadata_direction":"ltr","audio_languages":["eng"],"cast":[{"name":"Susan Sarandon"},{"name":"Aidan Devine"},{"name":"Cynthia Mace"}]}],"remaining":1} 

代码认为低于32且高于126的任何内容都是特殊字符。您需要为您的场景更新它。

答案 1 :(得分:0)

this post的帮助下。

您可以使用JSON.parse()解析字符串(如果您还没有将其作为对象),然后以递归方式遍历其所有属性。对于既不是对象也不是数组的属性,使用encodeURIComponent()对每个值进行编码。

DEMO:

这里是JSFiddle

<强> CODE:

从您问题中的第一个JSON字符串中考虑obj已解析的对象。以下是JSFiddle链接断开时的代码:

escapeObject(obj);
var escaped = JSON.stringify(obj);
document.getElementById("result").innerHTML = escaped;

function escapeObject(theObject) {
  var result = null;
  if(theObject instanceof Array) {
    for(var i = 0; i < theObject.length; i++) {
        result = escapeObject(theObject[i]);
        if (result) {
            break;
        }   
    }
  }
  else
  {        
      for(var prop in theObject) {    
        if (typeof theObject[prop] == typeof "") {
          var escValue = encodeURIComponent(theObject[prop]);
          theObject[prop] = escValue;  
        }
        if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
            result = escapeObject(theObject[prop]);
            if (result) {
                break;
            }
        }

    };
  }
  return result;
}