TypeScript parse json

60 TypeScript code examples are found related to "parse json".
Example 1
Source File: util.ts    From openapi-cop with MIT License 8 votes vote down vote up
export function parseJsonOrYaml(filePath: string, data: string): any {
  switch (path.extname(filePath)) {
    case '.json':
      return JSON.parse(data);
    case '.yaml':
    case '.yml':
      return yaml.safeLoad(data);
    case '.':
      throw new Error('Will not read a file that has no extension.');
    default:
      throw new Error('Wrong file extension.');
  }
}
Example 2
Source File: deep-parse.ts    From Adachi-BOT with MIT License 8 votes vote down vote up
export function deepParse( json: any ) {
	if ( typeof json === "string" ) {
		if ( isNumber( json ) ) {
			return parseInt( json );
		}
		try {
			return deepParse( JSON.parse( json ) );
		} catch ( err ) {
			return json;
		}
	} else if ( Array.isArray( json ) ) {
		return json.map( val => deepParse( val ) );
	} else if ( typeof json === "object" && json !== null ) {
		return Object.keys( json ).reduce(
			( pre, cur ) => {
				const value = json[cur];
				pre[cur] = isNumber( value ) ? value : deepParse( value );
				return pre;
			}, {}
		);
	} else {
		return json;
	}
}
Example 3
Source File: index.ts    From walletconnect-utils with MIT License 8 votes vote down vote up
export function safeJsonParse<T = any>(value: string): T | string {
  if (typeof value !== "string") {
    throw new Error(`Cannot safe json parse value of type ${typeof value}`);
  }
  try {
    return JSON.parse(value);
  } catch {
    return value;
  }
}
Example 4
Source File: utils.ts    From HomebridgeMagicHome-DynamicPlatform with Apache License 2.0 8 votes vote down vote up
//=================================================
// End Convert HSLtoRGB //

export function parseJson<T>(value: string, replacement: T): T {
  try {
    return <T>JSON.parse(value);
  } catch (_error) {
    return replacement;
  }
}
Example 5
Source File: utils.ts    From bitpay-browser-extension with MIT License 8 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function safelyParseJSON(json: any): object | undefined {
  let parsed;
  try {
    parsed = JSON.parse(json);
    // eslint-disable-next-line no-empty
  } catch (e) {}
  return parsed;
}
Example 6
Source File: project-contents-utils.ts    From utopia with MIT License 8 votes vote down vote up
function parsePackageJsonInner(
  packageJson: ProjectFile | undefined | null,
): Record<string, any> | null {
  if (packageJson != null && isTextFile(packageJson)) {
    try {
      return JSON.parse(packageJson.fileContents.code)
    } catch (e) {
      console.error('Invalid package.json contents.', e)
      return null
    }
  } else {
    return null
  }
}
Example 7
Source File: package-parser-utils.ts    From utopia with MIT License 8 votes vote down vote up
export function parseStringToJSON(value: unknown): ParseResult<AnyJson> {
  return flatMapEither((jsonText) => {
    try {
      const parsed = JSON.parse(jsonText)
      return right(parsed)
    } catch (error) {
      return left(descriptionParseError('Failed to parse JSON.'))
    }
  }, parseString(value))
}
Example 8
Source File: Serialization.ts    From eris-fleet with MIT License 8 votes vote down vote up
parseJSON = (json: string): any => {
	return JSON.parse(json, (key, value) => {
		if (typeof value === "string") {
			if (value.startsWith("BIGINT::")) {
				return BigInt(value.substring(8)); 
			} else if (value.startsWith("UNDEFINED::")) {
				return undefined;
			}
		}
		return value;
	});
}
Example 9
Source File: persistState.ts    From nosgestesclimat-site with MIT License 8 votes vote down vote up
// A wrapper for "JSON.parse()"" to support "undefined" value

function parseJSON<T>(value: string | null): T | undefined {
	try {
		return value === 'undefined' ? undefined : JSON.parse(value ?? '')
	} catch {
		console.log('parsing error on', { value })

		return undefined
	}
}
Example 10
Source File: normalizeBuilderNode.ts    From next-core with GNU General Public License v3.0 8 votes vote down vote up
function safeJsonParse(value: string): unknown {
  if (!value) {
    return;
  }
  try {
    return JSON.parse(value);
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error("JSON.parse() failed", value);
  }
}
Example 11
Source File: parse-json.ts    From etherspot-sdk with MIT License 8 votes vote down vote up
/**
 * @ignore
 */
export function parseJson<T>(raw: string, defaultValue: T = null): T {
  let result: T;
  try {
    result = JSON.parse(raw);
  } catch (err) {
    result = defaultValue;
  }

  return result;
}
Example 12
Source File: json.ts    From geonetwork-ui with GNU General Public License v2.0 8 votes vote down vote up
/**
 * This parser only supports arrays of simple flat objects with properties
 * @param text
 */
export function parseJson(text: string): Feature[] {
  const parsed = JSON.parse(text)
  if (!Array.isArray(parsed)) {
    throw new Error('Could not parse JSON, expected an array at root level')
  }
  return (parsed as any[]).map(jsonToGeojsonFeature)
}
Example 13
Source File: data-transform.ts    From gosling.js with MIT License 8 votes vote down vote up
// TODO: Get this data from the fetcher as a default with a flag variable.
export function parseSubJSON(_: JSONParseTransform, data: Datum[]): Datum[] {
    const { field, genomicField, baseGenomicField, genomicLengthField } = _;
    let output: Datum[] = Array.from(data);
    output = output
        .map((d: Datum) => {
            let newRows: Datum[] = JSON.parse(d[field] as string);

            newRows = newRows.map(row => {
                if (row[genomicField] && d[baseGenomicField]) {
                    row[`${genomicField}_start`] = +row[genomicField] + +d[baseGenomicField];
                    row[`${genomicField}_end`] = +row[genomicField] + +d[baseGenomicField] + +row[genomicLengthField];
                }

                return Object.assign(JSON.parse(JSON.stringify(d)), {
                    ...row,
                    [`${genomicField}_start`]: row[`${genomicField}_start`],
                    [`${genomicField}_end`]: row[`${genomicField}_end`],
                    type: row.type ?? row.variant ?? null,
                    isParsedRow: 'yes'
                });
            });

            return [d, ...newRows];
        })
        .reduce((a, b) => a.concat(b), []);
    return output;
}
Example 14
Source File: parseJSON.ts    From hoprnet with GNU General Public License v3.0 8 votes vote down vote up
/**
 * Parse JSON while recovering all Buffer elements
 * @param str JSON string
 */
export function parseJSON(str: string): object {
  return JSON.parse(str, (_key, value) => {
    if (value && value.type === 'Buffer') {
      return Buffer.from(value.data)
    }

    return value
  })
}
Example 15
Source File: miscellany.ts    From DefinitelyTyped-tools with MIT License 8 votes vote down vote up
export function parseJson<T>(text: string, predicate: (parsed: unknown) => parsed is T = (_): _ is T => true) {
  let parsed: unknown;
  try {
    parsed = JSON.parse(text);
  } catch (err) {
    throw new Error(`${(err as Error).message} due to JSON: ${text}`);
  }
  if (!predicate(parsed)) {
    throw new Error("Parsed JSON did not match required form");
  }
  return parsed;
}
Example 16
Source File: json.ts    From open-source with MIT License 8 votes vote down vote up
export function jsonParse(content: string): any {
  try {
    // parse the data
    return JSON.parse(content);
  } catch (e) {
    // filter any existing comments
    return JSON.parse(content.split('\n').filter(line => !line.match(/^\s*?\//)).join('\n'));
  }
}
Example 17
Source File: request.ts    From oasis-wallet-web with Apache License 2.0 8 votes vote down vote up
/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response: Response) {
  if (response.status === 204 || response.status === 205) {
    return null
  }
  return response.json()
}
Example 18
Source File: binary.ts    From eosio-contract-api with GNU Affero General Public License v3.0 8 votes vote down vote up
export function parseJsonObject(data: string): any {
    try {
        const result = JSON.parse(data);

        if (typeof result === 'object' && !Array.isArray(result)) {
            return result;
        }

        return {};
    } catch {
        return {};
    }
}
Example 19
Source File: utils.ts    From professor-prebid with Apache License 2.0 8 votes vote down vote up
safelyParseJSON = (data: object | string): object => {
  if (typeof data === 'object') {
    return data;
  }

  try {
    return JSON.parse(data);
  } catch (e) {
    console.error(`safelyParseJSON failed with data `, data);
    return {};
  }
}
Example 20
Source File: request.ts    From react-boilerplate-cra-template with MIT License 8 votes vote down vote up
/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response: Response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  return response.json();
}
Example 21
Source File: utils.ts    From ngm with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
/**
 * Returns object parsed from string or undefined
 * @param {string} string
 * @returns {object|undefined}
 */
export function parseJson(string) {
  try {
    return JSON.parse(string);
  } catch (e) {
    return undefined;
  }
}
Example 22
Source File: try-parse-json.function.ts    From nest-amqp with MIT License 8 votes vote down vote up
/**
 * Try to parse a string value into an object. If the parsing fails then `false`
 * value will be returned.
 *
 * @param {string} jsonString Object as string.
 * @return {(T|undefined)} Parsed object or undefined.
 */
export function tryParseJSON<T = any>(jsonString: string): T | undefined {
  try {
    const o = JSON.parse(jsonString);

    // Handle non-exception-throwing cases:
    // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
    // but... JSON.parse(null) returns null, and typeof null === "object",
    // so we must check for that, too. Thankfully, null is falsy, so this suffices:
    if (o && typeof o === 'object') {
      return o;
    }
  } catch (e) {
    return undefined;
  }
}
Example 23
Source File: explore.ts    From grafana-chinese with Apache License 2.0 8 votes vote down vote up
safeParseJson = (text: string) => {
  if (!text) {
    return;
  }

  try {
    return JSON.parse(decodeURI(text));
  } catch (error) {
    console.error(error);
  }
}
Example 24
Source File: util.ts    From angular-git-info with MIT License 8 votes vote down vote up
export function parseJsonAtPath(tree: Tree, path: string): JsonAstObject {
    const buffer = tree.read(path);

    if (buffer === null) {
        throw new SchematicsException('Could not read package.json.');
    }

    const content = buffer.toString();

    const json = parseJsonAst(content, JsonParseMode.Strict);
    if (json.kind != 'object') {
        throw new SchematicsException(
            'Invalid package.json. Was expecting an object'
        );
    }

    return json;
}
Example 25
Source File: index.ts    From nanogram.js with MIT License 8 votes vote down vote up
parseJSON = <T>(content: string, useRegExp: boolean): T => {
  try {
    let data = content;

    if (useRegExp) {
      data = SHARED_DATA_REG_EXP.exec(content)[1];
    }

    return JSON.parse(data) as T;
  } catch (error) {
    throw new Error(error);
  }
}
Example 26
Source File: migration.service.ts    From Cromwell with MIT License 7 votes vote down vote up
private parseJson(json: any) {
        if (!json) return null;
        if (typeof json === 'object') return json;
        if (typeof json === 'string') {
            try {
                return JSON.parse(json);
            } catch (error) {
                getLogger().error(error);
            }
        }
        return null;
    }
Example 27
Source File: commons.ts    From foundryvtt-lancer with GNU General Public License v3.0 7 votes vote down vote up
// JSON parses a string, returning null instead of an exception on a failed parse
export function safe_json_parse(str: string): any | null {
  try {
    let result = JSON.parse(str);
    return result;
  } catch {
    return null;
  }
}
Example 28
Source File: ConfigBuilder.ts    From context-mod with MIT License 7 votes vote down vote up
parseFilterJson = <T>(addToFilter: FilterJsonFuncArg<T>) => (val: MinimalOrFullFilterJson<T> | undefined) => {
    if (val === undefined) {
        return;
    }
    if (Array.isArray(val)) {
        for (const v of val) {
            addToFilter(v);
        }
    } else {
        const {include = [], exclude = []} = val;
        for (const v of include) {
            addToFilter(v);
        }
        for (const v of exclude) {
            addToFilter(v);
        }
    }
}
Example 29
Source File: utils.ts    From mockiavelli with MIT License 7 votes vote down vote up
export function tryJsonParse(data: any): any | undefined {
    try {
        return JSON.parse(data);
    } catch (e) {
        return data;
    }
}
Example 30
Source File: zip.service.ts    From kontent-backup-manager-js with MIT License 7 votes vote down vote up
private async readAndParseJsonFile(fileContents: any, filename: string): Promise<any> {
        const files = fileContents.files;
        const file = files[filename];

        if (!file) {
            throw Error(`Invalid file '${filename}'`);
        }

        const text = await file.async('text');

        return JSON.parse(text);
    }
Example 31
Source File: dataTypeParser.ts    From ngx-dynamic-hooks with MIT License 7 votes vote down vote up
/**
   * In order to successfully parse a data type string with JSON.parse(), it needs to follow certain formatting rules.
   * This functions ensures that these are followed and corrects the input if not.
   *
   * @param JSONString - The string to be given to JSON.parse()
   * @param unescapeStrings - Whether to unescape the strings of this JSON
   */
  parseAsJSON(JSONString: string, unescapeStrings: boolean = true): any {

    // Find all single- and grave-quote-delimited strings and convert them to double quote strings
    const singleQuoteStringRegex = /\'(\\.|[^\'])*?\'/gm;
    JSONString = JSONString.replace(singleQuoteStringRegex, match => {
      return '"' + match.slice(1, -1) + '"';
    });
    const graveQuoteStringRegex = /\`(\\.|[^\`])*?\`/gm;
    JSONString = JSONString.replace(graveQuoteStringRegex, match => {
      return '"' + match.slice(1, -1) + '"';
    });

    // Add double-quotes around JSON property names where still missing
    const JSONPropertyRegex = /"?([a-z0-9A-Z_]+)"?\s*:/g;
    JSONString = JSONString.replace(JSONPropertyRegex, '"$1": ');

    // Prevent setting protected properties
    if (JSONString.match(/"?__proto__"?\s*:/g)) {
      throw Error('Setting the "__proto__" property in a hook input object is not allowed.');
    }
    if (JSONString.match(/"?prototype"?\s*:/g)) {
      throw Error('Setting the "prototype" property in a hook input object is not allowed.');
    }
    if (JSONString.match(/"?constructor"?\s*:/g)) {
      throw Error('Setting the "constructor" property in a hook input object is not allowed.');
    }

    // Replace undefined with null
    JSONString = this.replaceValuesInJSONString(JSONString, 'undefined', match => 'null');

    // Replace context vars with string placeholders
    JSONString = this.replaceValuesInJSONString(JSONString, regexes.contextVariableRegex, (match) => {
      return '"' + this.dataTypeEncoder.transformContextVarIntoPlacerholder(match) + '"';
    });

    // Replace $event with string placeholders
    JSONString = this.replaceValuesInJSONString(JSONString, '\\$event', match => '"__EVENT__"');

    // PARSE
    const json = JSON.parse(JSONString);

    // Decode all strings that are not context vars or the event object
    this.decodeJSONStrings(json, unescapeStrings);

    return json;
  }
Example 32
Source File: file-system.service.ts    From mylog14 with GNU General Public License v3.0 7 votes vote down vote up
getJsonData(filename: string, parse = true, dir = FilesystemDirectory.Data): Observable<any> {
    const readFile$ = defer(() => from(Filesystem.readFile({
      encoding: this.defaultEncoding,
      path: filename,
      directory: dir,
    })));
    return readFile$
      .pipe(
        catchError(() => of({ data: null })),
        map(readResult => readResult.data),
        filter(data => data != null),
        defaultIfEmpty('{}'),
        map(data => parse ? JSON.parse(data) : data),
      );
  }
Example 33
Source File: helpers.ts    From chain-js with MIT License 7 votes vote down vote up
/**
 * The reviver function passed into JSON.parse to implement custom type conversions.
 * If the value is a previously stringified buffer we convert it to a Buffer,
 * If its an object of numbers, we convert to UInt8Array {"0":2,"1":209,"2":8 ...}
 * otherwise return the value
 */
export function jsonParseComplexObjectReviver(key: string, value: any) {
  // Convert Buffer
  if (
    value !== null &&
    typeof value === 'object' &&
    'type' in value &&
    value.type === 'Buffer' &&
    'data' in value &&
    Array.isArray(value.data)
  ) {
    return Buffer.from(value.data)
  }

  // Convert number array to UInt8Array e.g. {"0":2,"1":209,"2":8 ...}
  if (value !== null && typeof value === 'object' && !Array.isArray(value) && '0' in value && isANumber(value['0'])) {
    const values = Object.entries(value).map(([, val]) => val)
    // if array only has 8-bit numbers, convert it to UInt8Array
    if (values.every(val => isANumber(val) || val < 256)) {
      return new Uint8Array(values as number[])
    }
  }

  // Return parsed value without modifying
  return value
}
Example 34
Source File: helpers.ts    From chain-js with MIT License 7 votes vote down vote up
/** Parses a stringified string into a JSON object
 *  Returns Null if parse fails */
export function tryParseJSON(value: any) {
  if (!value || !isAString(value) || value.trim() === '') return null
  try {
    const parsed = JSON.parse(value, jsonParseComplexObjectReviver)
    if (parsed && typeof parsed === 'object') return parsed
  } catch (error) {
    // TODO: should log trace this detail: ('error parsing JSON', { jsonString, doubleQuotes, error });
  }
  return null
}
Example 35
Source File: useLocalStorage.ts    From crowdsource-dataplatform with MIT License 7 votes vote down vote up
parseJSON = <T>(stringifiedJSON: string | null, fallbackValue: T) => {
  try {
    if (!stringifiedJSON) {
      return fallbackValue;
    }

    return JSON.parse(stringifiedJSON);
  } catch (e) {
    return stringifiedJSON;
  }
}
Example 36
Source File: utils.ts    From WELearnHelper with GNU General Public License v3.0 7 votes vote down vote up
export function parseResponse(json: QuestionResponse) {
    console.log(json);

    let status = "";
    switch (json.status) {
        case 0:
            status = "新增收录题目,未收录答案";
            break;
        case 1:
            status = "新增收录题目,且收录答案";
            addMessage(status, "info");
            addMessage(`用户${store.USER_SETTINGS.userAccount}积分+1`, "info");
            break;
        case 2:
            status = "服务器已有题目,新增答案";
            addMessage(status, "info");
            addMessage(`用户${store.USER_SETTINGS.userAccount}积分+1`, "info");
            break;
        case 3:
            status = "服务器已有答案,返回答案";
            break;
        case 4:
            status = "服务器已有题目,没有答案";
            break;
        case 5:
            status = "服务器没有题目,没有答案";
            break;
        case 6:
            status = "没有标答,返回最可能答案";
            break;
    }
    // addMessage(status, "info");

    let answer = json.answer;
    switch (json.status) {
        case 3:
            addMessage(answer as string, "success");
            break;
        case 4:
        //fallthrough
        case 5:
            addMessage("尚未收录答案", "error");
            break;
        case 6:
            for (let [option, possibility] of Object.entries(<string>answer)) {
                addMessage(`${possibility} ${option}`, "success");
            }
    }

    if (store.messages)
        if (store.messages[store.messages.length - 1].info)
            //前一条消息为空不添加
            addMessage("", "hr");
}
Example 37
Source File: text.ts    From S2 with MIT License 7 votes vote down vote up
safeJsonParse = (val: string) => {
  try {
    return JSON.parse(val);
  } catch (err) {
    return null;
  }
}
Example 38
Source File: completeSnippets.ts    From amazon-states-language-service with MIT License 7 votes vote down vote up
function parseSnippetsFromJson(json: Snippet[]): CompletionItem[] {
    return json.map(snippet => {
        const item = CompletionItem.create(snippet.name)
        item.kind = CompletionItemKind.Snippet
        item.insertTextFormat = InsertTextFormat.Snippet
        item.insertText = snippet.body.join('\n')
        item.documentation = snippet.description

        return item
    })
}
Example 39
Source File: AjaxObservable.ts    From amazon-kinesis-video-streams-webrtc-sdk-js-with-amazon-cognito with MIT No Attribution 7 votes vote down vote up
function parseJson(xhr: XMLHttpRequest) {
  // HACK(benlesh): TypeScript shennanigans
  // tslint:disable-next-line:no-any XMLHttpRequest is defined to always have 'response' inferring xhr as never for the else clause.
  if ('response' in (xhr as any)) {
    //IE does not support json as responseType, parse it internally
    return xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
  } else {
    return JSON.parse((xhr as any).responseText || 'null');
  }
}
Example 40
Source File: core.ts    From backstage with Apache License 2.0 7 votes vote down vote up
/**
 * Parse the json response from Gerrit and strip the magic prefix.
 *
 * @remarks
 *
 * To prevent against XSSI attacks the JSON response body from Gerrit starts
 * with a magic prefix that must be stripped before it can be fed to a JSON
 * parser.
 *
 * @param response - An API response.
 * @public
 */
export async function parseGerritJsonResponse(
  response: Response,
): Promise<unknown> {
  const responseBody = await response.text();
  if (responseBody.startsWith(GERRIT_BODY_PREFIX)) {
    try {
      return JSON.parse(responseBody.slice(GERRIT_BODY_PREFIX.length));
    } catch (ex) {
      throw new Error(
        `Invalid response from Gerrit: ${responseBody.slice(0, 10)} - ${ex}`,
      );
    }
  }
  throw new Error(
    `Gerrit JSON body prefix missing. Found: ${responseBody.slice(0, 10)}`,
  );
}
Example 41
Source File: strategy.ts    From backstage with Apache License 2.0 7 votes vote down vote up
static parse(json: string): Profile {
    const resp = JSON.parse(json) as ProfileResponse;

    return {
      id: resp.account_id,
      provider: 'atlassian',
      username: resp.nickname,
      displayName: resp.name,
      emails: [{ value: resp.email }],
      photos: [{ value: resp.picture }],
    };
  }
Example 42
Source File: Utils.ts    From coddx-alpha with MIT License 7 votes vote down vote up
export function parseJsonString(jsonString: string) {
  if (!jsonString || !jsonString.trim()) {
    return {};
  }
  let useParams = {};
  try {
    useParams = JSON.parse(jsonString.trim());
  } catch {}
  return useParams;
}
Example 43
Source File: fetch-packages.ts    From utopia with MIT License 7 votes vote down vote up
function parseNameVersionFromParsedPackageJson(
  parsedJSON: AnyJson,
): ParseResult<PackageJsonResolvedPackageFields> {
  return applicative3Either(
    (name, version, resolvedUrl) => {
      return {
        name: name,
        version: version,
        resolvedUrl: resolvedUrl,
      }
    },
    objectKeyParser(parseString, 'name')(parsedJSON),
    objectKeyParser(parseString, 'version')(parsedJSON),
    optionalObjectKeyParser(parseString, '_resolved')(parsedJSON),
  )
}
Example 44
Source File: module-resolution.ts    From utopia with MIT License 7 votes vote down vote up
export function parsePartialPackageJsonDefinition(
  value: unknown,
): ParseResult<PartialPackageJsonDefinition> {
  return applicative4Either(
    (name, main, module, browser) => {
      let result: PartialPackageJsonDefinition = {}
      setOptionalProp(result, 'name', name)
      setOptionalProp(result, 'main', main)
      setOptionalProp(result, 'module', module)
      setOptionalProp(result, 'browser', browser)
      return result
    },
    optionalObjectKeyParser(parseString, 'name')(value),
    optionalObjectKeyParser(parseString, 'main')(value),
    optionalObjectKeyParser(parseString, 'module')(value),
    optionalObjectKeyParser(
      parseAlternative<string | MapLike<string | false>>(
        [
          parseString,
          parseObject(
            parseAlternative<string | false>(
              [parseString, parseFalse],
              `package.browser replacement entries must be either string or 'false' for ignoring a package`,
            ),
          ),
        ],
        'package.browser field must either be a string or an object with type {[key: string]: string}',
      ),
      'browser',
    )(value),
  )
}
Example 45
Source File: project-file-types.ts    From utopia with MIT License 7 votes vote down vote up
export function parseFailure(
  diagnostics: Array<ErrorMessage> | null,
  parsedJSON: ParsedJSONFailure | null,
  errorMessage: string | null,
  errorMessages: Array<ErrorMessage>,
): ParseFailure {
  return {
    type: 'PARSE_FAILURE',
    diagnostics: diagnostics,
    parsedJSONFailure: parsedJSON,
    errorMessage: errorMessage,
    errorMessages: errorMessages,
  }
}
Example 46
Source File: utils.ts    From utopia with MIT License 7 votes vote down vote up
function jsonParseOrNull(jsonString: string): any | null {
  try {
    return JSON.parse(jsonString)
  } catch (e) {
    return null
  }
}
Example 47
Source File: Utils.ts    From craft-extension-inspirations with MIT License 7 votes vote down vote up
export function safeJsonParse(jsonStr: string | null | undefined): unknown | null {
  if (jsonStr == null || jsonStr === "") {
    return null;
  }
  try {
    return JSON.parse(jsonStr);
  } catch (e) {
    const message = e instanceof Error ? e.message : null;
    console.error("JsonSyntaxError", message);
    return null;
  }
}
Example 48
Source File: settings-parser.ts    From vs-code-conan with MIT License 7 votes vote down vote up
private parseProfile(rawJson: string):Map<string, Profile>|undefined{
        const jsonObj: { profiles: ProfileJson[] } = JSON.parse(rawJson);
        if(!jsonObj.profiles){
            return this.profiles;
        }
        let profiles = new Map<string, Profile>();
        for (let profile of jsonObj.profiles){
            if(this.checkProfile(profile,profiles)){
                profiles.set(profile.name,new Profile(profile));
            }
        }
        return profiles;
    }
Example 49
Source File: settings-parser.ts    From vs-code-conan with MIT License 7 votes vote down vote up
private parseWorkspace(rawJson: string):Map<string, Workspace> | undefined{
        const jsonObj: { workspace: WorkspaceJson[] } = JSON.parse(rawJson);
        if(!jsonObj.workspace){
            return this.workspaces;
        }
        let workspaces = new Map<string, Workspace>();
        for (let workspace of jsonObj.workspace){
            if(this.checkProfile(workspace,workspaces)){
                workspaces.set(workspace.name,new Workspace(workspace));
            }
        }
        return workspaces;
    }
Example 50
Source File: utils.ts    From dora with MIT License 7 votes vote down vote up
export function safeJsonParse(data: string) {
  try {
    return JSON.parse(data);
  } catch (_) {
    return null;
  }
}
Example 51
Source File: bounding-box-file-types.ts    From edge-impulse-cli with Apache License 2.0 7 votes vote down vote up
export function parseBoundingBoxLabels(jsonFile: string) {
    let data = <ExportBoundingBoxesFile>JSON.parse(jsonFile);
    if (data.version !== 1) {
        throw new Error('Invalid version');
    }
    if (data.type !== 'bounding-box-labels') {
        throw new Error('Invalid type');
    }
    if (typeof data.boundingBoxes !== 'object') {
        throw new Error('boundingBoxes is not an object');
    }
    return data;
}
Example 52
Source File: exceptionHandler.ts    From ts-di-starter with MIT License 7 votes vote down vote up
/**
   * Express middleware for json body parser errors.
   * From here: {@link https://github.com/expressjs/body-parser/issues/122#issuecomment-328190379}
   *
   * @param {Error|RError|object} error unhandled error
   * @param {Request} request express request
   * @param {Response} response express response
   * @param {Function} next
   * @returns {Promise<void>}
   */
  async handleJsonParseError(error, request, response, next): Promise<void> {
    if (error.type && error.type === 'entity.parse.failed') {
      await this.services.responseBuilder.respond(response, new Err('Could not parse JSON input', HTTP_STATUS.BAD_REQUEST, error.body));
      return;
    }

    next(error);
  }
Example 53
Source File: blob.ts    From excalidraw with MIT License 7 votes vote down vote up
parseLibraryJSON = (
  json: string,
  defaultStatus: LibraryItem["status"] = "unpublished",
) => {
  const data: ImportedLibraryData | undefined = JSON.parse(json);
  if (!isValidLibrary(data)) {
    throw new Error("Invalid library");
  }
  const libraryItems = data.libraryItems || data.library;
  return restoreLibraryItems(libraryItems, defaultStatus);
}
Example 54
Source File: lib.ts    From Json-to-Dart-Model with MIT License 7 votes vote down vote up
export function parseJSON(json: string): { [key: string]: any } {
  const tryEval = (str: any) => eval(`const a = ${str}; a`);

  try {
    return jsonc.parse(json);
  } catch (ignored) { }

  try {
    return tryEval(json);
  } catch (error) {
    return new Error('Selected string is not a valid JSON');
  }
}
Example 55
Source File: syntax.ts    From Json-to-Dart-Model with MIT License 7 votes vote down vote up
private jsonParseFunc(input: Input): string {
    const mapValue = input.jsonCodecs ? 'data' : 'json';
    const blockBody = (): string => {
      let sb = '';
      sb += printLine(`factory ${this.name}`, 2, 1);
      sb += printLine(`.from${suffix(input)}(${jsonMapType(input)} ${mapValue}) {`);
      sb += printLine(`return ${this.name}(\n`, 1, 2);
      sb += this.getFields((f, k) => {
        // Check forced type for only not primitive type.
        const key = k.match('.') && !f.isList && f.type && !f.isPrimitive ? f.type : k;
        return `\t\t\t${joinAsClass(f.getName(this._privateFields), jsonParseValue(key, f, input))}`;
      }).join('\n');
      sb += printLine(');', 1, 2);
      sb += printLine('}\n\n', 1, 1);
      return sb;
    };

    const expressionBody = (): string => {
      let sb = '';
      sb += printLine(`factory ${this.name}`, 2, 1);
      sb += printLine(`.from${suffix(input)}(${jsonMapType(input)} ${mapValue}) => `);
      sb += printLine(`${this.name}(\n`);
      sb += this.getFields((f, k) => {
        // Check forced type for only not primitive type.
        const key = k.match('.') && !f.isList && f.type && !f.isPrimitive ? f.type : k;
        return `\t\t\t\t${joinAsClass(f.getName(this._privateFields), jsonParseValue(key, f, input))}`;
      }).join('\n');
      sb += printLine(');', 1, 3);
      return sb;
    };

    const line = expressionBody().substring(0, expressionBody().indexOf('(\n') + 1);

    return line.length > 78 ? blockBody() : expressionBody();
  }
Example 56
Source File: syntax.ts    From Json-to-Dart-Model with MIT License 7 votes vote down vote up
/**
   * Generate function for json_serializable and freezed.
   * @param freezed force to generate expression body (required for freezed generator).
   */
  private codeGenJsonParseFunc(input: Input): string {
    const expressionBody = (): string => {
      let sb = '';
      sb += printLine(`factory ${this.name}.`, 2, 1);
      sb += 'fromJson(Map<String, dynamic> json) => ';
      sb += `_$${this.name}FromJson(json);`;
      return sb;
    };
    const blockBody = (): string => {
      let sb = '';
      sb += printLine(`factory ${this.name}.`, 2, 1);
      sb += 'fromJson(Map<String, dynamic> json) {';
      sb += printLine(`return _$${this.name}FromJson(json);`, 1, 2);
      sb += printLine('}', 1, 1);
      return sb;
    };
    return expressionBody().length > 78 && !input.freezed
      ? blockBody()
      : expressionBody();
  }
Example 57
Source File: syntax.ts    From Json-to-Dart-Model with MIT License 7 votes vote down vote up
export function jsonParseValue(
  key: string,
  typeDef: TypeDefinition,
  input: Input
) {
  const jsonValue = valueFromJson(key, input);
  const nullable = questionMark(input, typeDef);
  const isDouble = typeDef.type === 'double';
  const dafaultVal = typeDef.defaultValue
    ? `${isDouble ? '' : '?'} ?? ${defaultValue(typeDef, input.nullSafety, false).replace(/=|const/gi, '').trim()}`
    : '';
  const IfNull = `${includeIfNull(jsonValue, input)}`;
  let formatedValue = '';

  if (typeDef.isPrimitive) {
    const required = typeDef.required && input.avoidDynamicTypes ? '!' : '';

    if (typeDef.isDate) {
      formatedValue = jsonParseClass(key, typeDef, input);
    } else {
      if (!typeDef.nullable && !typeDef.isList) {
        formatedValue = `${jsonValue}`;
      } if (isDouble) {
        const nullableDouble = input.nullSafety && !typeDef.required ? '?' : '';
        formatedValue = `${IfNull}(${jsonValue}${required} as num${nullableDouble})${nullableDouble}.toDouble()` + dafaultVal;
      } else {
        formatedValue = `${IfNull}${jsonValue}${required} as ${typeDef.type}` + nullable + dafaultVal;
      }
    }
  } else {
    formatedValue = jsonParseClass(key, typeDef, input);
  }
  return formatedValue;
}
Example 58
Source File: RosettaConstructionParseRequest.ts    From stacks-blockchain-api with GNU General Public License v3.0 7 votes vote down vote up
export function RosettaConstructionParseRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): RosettaConstructionParseRequest {
    if ((json === undefined) || (json === null)) {
        return json;
    }
    return {
        
        'network_identifier': NetworkIdentifierFromJSON(json['network_identifier']),
        'signed': json['signed'],
        'transaction': json['transaction'],
    };
}
Example 59
Source File: RosettaConstructionParseRequest.ts    From stacks-blockchain-api with GNU General Public License v3.0 7 votes vote down vote up
export function RosettaConstructionParseRequestToJSON(value?: RosettaConstructionParseRequest | null): any {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    return {
        
        'network_identifier': NetworkIdentifierToJSON(value.network_identifier),
        'signed': value.signed,
        'transaction': value.transaction,
    };
}
Example 60
Source File: RosettaConstructionParseResponse.ts    From stacks-blockchain-api with GNU General Public License v3.0 7 votes vote down vote up
export function RosettaConstructionParseResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): RosettaConstructionParseResponse {
    if ((json === undefined) || (json === null)) {
        return json;
    }
    return {
        
        'operations': ((json['operations'] as Array<any>).map(RosettaOperationFromJSON)),
        'signers': !exists(json, 'signers') ? undefined : json['signers'],
        'account_identifier_signers': !exists(json, 'account_identifier_signers') ? undefined : ((json['account_identifier_signers'] as Array<any>).map(RosettaAccountFromJSON)),
    };
}