sourcecode

평가 없이 "완화된" JSON 구문 분석

codebag 2023. 2. 22. 21:53
반응형

평가 없이 "완화된" JSON 구문 분석

"완화된" JSON을 해석하면서 악을 피하는 가장 쉬운 방법은 무엇입니까?eval?

다음은 오류를 발생시킵니다.

JSON.parse("{muh: 2}");

적절한 JSON에는 다음과 같은 따옴표가 붙어야 합니다.{"muh": 2}


JSON 명령어를 노드 서버에 쓸 때 사용하는 단순한 테스트 인터페이스입니다.지금까지는 단순히eval어차피 시험 신청일 뿐이니까.하지만 프로젝트 전체에 JSHint를 사용하는 것은 계속 신경이 쓰인다.eval그래서 여전히 키의 구문을 완화할 수 있는 안전한 대안을 원합니다.

PS: 테스트 어플리케이션만을 위해서 파서를 직접 쓰고 싶지는 않습니다:-)

정규 표현 치환을 사용하여 JSON을 삭제할 수 있습니다.

var badJson = "{muh: 2}";
var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ');
JSON.parse(correctJson);

저를 소개해주셨기 때문에 이미 알고 계시겠지만, 여기서 문서화하는 것이 좋을 것 같습니다.

JS가 유효한 "여유한" JSON을 쓸 수 있기를 원했기 때문에 Douglas Crockford의 평가판이 없는 json_parse.js를 ES5 기능을 지원하도록 확장했습니다.

https://github.com/aseemk/json5

이 모듈은 npm에 제공되며 네이티브의 드롭인 대체품으로 사용할 수 있습니다.JSON.parse()방법(그것들)stringify()표준 JSON을 출력합니다).

이게 도움이 됐으면 좋겠네요!

이게 내가 해야 할 일이야.나는 @Arnaud를 확장했다.Weil의 답변과 지원 추가:값은 다음과 같습니다.

var badJSON = '{one : "1:1", two : { three: \'3:3\' }}';

var fixedJSON = badJSON

	// Replace ":" with "@colon@" if it's between double-quotes
	.replace(/:\s*"([^"]*)"/g, function(match, p1) {
		return ': "' + p1.replace(/:/g, '@colon@') + '"';
	})

	// Replace ":" with "@colon@" if it's between single-quotes
	.replace(/:\s*'([^']*)'/g, function(match, p1) {
		return ': "' + p1.replace(/:/g, '@colon@') + '"';
	})

	// Add double-quotes around any tokens before the remaining ":"
	.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')

	// Turn "@colon@" back into ":"
	.replace(/@colon@/g, ':')
;

console.log('Before: ' + badJSON);
console.log('After: ' + fixedJSON);
console.log(JSON.parse(fixedJSON));

다음과 같은 출력이 생성됩니다.

Before: {one : "1:1", two : { three: '3:3' }}
After: {"one":  "1:1", "two":  { "three":  "3:3" }}
{
  "one": "1:1",
  "two": {
    "three": "3:3"
  }
}

문자열을 쓸 때 키를 따옴표로 묶을 수 없는 경우 JSON.parse-를 사용하기 전에 따옴표로 묶을 수 있습니다.

var s= "{muh: 2,mah:3,moh:4}";
s= s.replace(/([a-z][^:]*)(?=\s*:)/g, '"$1"');

var o= JSON.parse(s);
/*  returned value:[object Object] */
JSON.stringify(o)
/*  returned value: (String){
    "muh":2, "mah":3, "moh":4
}

Plamenco의 really-time-json(https://www.npmjs.com/package/really-relaxed-json)에서는 쉼표, 쉼표, 댓글, 여러 줄 문자열 등을 사용할 수 있습니다.

다음은 사양 http://www.relaxedjson.org 입니다.

일부 온라인 파서:
http://www.relaxedjson.org/docs/converter.html

'bad json'이 프리 로드되어 있습니다.

{one : "1:1", two : { three: '3:3' }}

부정한 JSON

'worse json'까지 프리로드(쉼표 없음)

{one : '1:1' two : { three: '3:3' }}

더 나쁜 JSON

terrible json(콤마, 따옴표, 이스케이프 콜론 없음)이 프리 로드되어 있습니다.

{one : 1\:1 two : {three : 3\:3}}

끔찍한 JSON

키의 마침표, 키 값의 콜론 및 임의의 공백(JSON 오브젝트 키 값은 다루지 않지만)을 처리하기 위해 Arnaud의 솔루션을 약간 수정했습니다.

var badJson = `{
    firstKey: "http://fdskljflksf",
    second.Key: true, thirdKey:
    5, fourthKey: "hello"
}`;


/*
    \s*
        any amount of whitespace
    (['"])?
        group 1: optional quotation
    ([a-z0-9A-Z_\.]+)
        group 2: at least one value key character
    (['"])?
        group 3: optional quotation
    \s*
        any amount of whitespace
    :
        a colon literal
    ([^,\}]+)
        group 4: at least one character of the key value (strings assumed to be quoted), ends on the following comma or closing brace
    (,)?
        group 5: optional comma
*/
var correctJson = badJson.replace(/\s*(['"])?([a-z0-9A-Z_\.]+)(['"])?\s*:([^,\}]+)(,)?/g, '"$2": $4$5');
JSON.parse(correctJson);

언급URL : https://stackoverflow.com/questions/9637517/parsing-relaxed-json-without-eval

반응형