Parse a JSON-LD document

@param string $jsonLDDocSource JSON-LD document

@return array Items
347050
protected function parseDocument($jsonLDDocSource)
    {
        // Unserialize the JSON-LD document
        $jsonLDDoc = @json_decode($jsonLDDocSource);

        // If this is not a valid JSON document: Return
        if (!is_object($jsonLDDoc) && !is_array($jsonLDDoc)) {
            $this->logger->error('Skipping invalid JSON-LD document');

            return [];
        }

        // Parse the document
        return array_filter(
            is_array($jsonLDDoc) ?
                array_map([$this, 'parseRootNode'], $jsonLDDoc) : [$this->parseRootNode($jsonLDDoc)]
        );
    }
1091121
protected function searchUrlPatterns(\stdClass $json, array $patterns)
    {
        $errors = array();
        foreach ($json->packages as $package) {
            if (!isset($package->source)) {
                $this->verbose('Source not found in "' . $package->name . "\"\n", OutputInterface::VERBOSITY_VERBOSE);
                $url = '';
            }else{
                $url = $package->source->url;
            }

            if (!$this->doesUrlMatchToAtLeastOnePattern($url, $patterns)) {
                $errors[$package->name] = $url;
            }
        }

        return $errors;
    }
62549
function JsonFind(doc) {
  const possibleJson = JSON.stringify(doc);

  if (possibleJson === undefined) {
    throw new Error('Object is invalid JSON');
  } else if (isAtom(doc) || doc === null) {
    return doc;
  } else {
    return Object.assign(Object.create(JSON_DATA), doc);
  }
}
1365703
public static function parse( $doc, $url ) {
		if ( ! $doc ) {
			return array();
		}
		$xpath = new DOMXPath( $doc );

		$jsonld = array();
		foreach ( $xpath->query( "//script[@type='application/ld+json']" ) as $script ) {
			$jsonld = json_decode( $script->textContent, true ); // phpcs:ignore
		}
		$meta = array();
		// Look for OGP properties
		foreach ( $xpath->query( '//meta[(@name or @property) and @content]' ) as $tag ) {
			$meta_name = self::limit_string( $tag->getAttribute( 'property' ) );
			if ( ! $meta_name ) {
				$meta_name = self::limit_string( $tag->getAttribute( 'name' ) );
			}
			$meta_value = $tag->getAttribute( 'content' );

			// Sanity check. $key is usually things like 'title', 'description', 'keywords', etc.
			if ( strlen( $meta_name ) > 200 ) {
				continue;
			}
			// Decode known JSON encoded properties
			if ( in_array( $meta_name, array( 'parsely-page', 'parsely-metadata' ), true ) ) {
				$json = json_decode( $meta_value, true );
				if ( is_array( $json ) ) {
					$meta_value = $json;
				}
			}
			$meta = self::set( $meta, $meta_name, $meta_value );
		}

		// Fetch and gather <img> data.
		$images = array();
		foreach ( $xpath->query( '//img[@src]' ) as $image ) {
			$src = self::limit_img( $image->getAttribute( 'src' ), $url );
			if ( ! empty( $src ) ) {
				$images[] = $src;
			}
		}

		// Fetch and gather <video> data.
		$videos = array();
		foreach ( $xpath->query( '//video' ) as $video ) {
			$src = $video->getAttribute( 'src' );
			if ( ! empty( $src ) ) {
				$videos = $src;
			}
		}

		// Fetch and gather <audio> data.
		$audios = array();

		foreach ( $xpath->query( '//audio' ) as $audio ) {
			$src = $audio->getAttribute( 'src' );
			if ( ! empty( $src ) ) {
				$audios[] = $src;
			}
		}
		foreach ( $xpath->query( '//figure' ) as $audio ) {
			$src = $audio->getAttribute( 'data-audio-url' );
			if ( ! empty( $src ) ) {
				$audios[] = $src;
			}
		}

		// Fetch and gather <iframe> data.
		$embeds = array();

		foreach ( $xpath->query( '//iframe[@src]' ) as $embed ) {
			$src = self::limit_embed( $embed->getAttribute( 'src' ), $url );
			if ( ! empty( $src ) ) {
				$embeds[] = $src;
			}
		}

		// Fetch and gather <link> data.
		$links = array();

		foreach ( $xpath->query( '//link[@rel and @href]' ) as $link ) {
			$rel = $link->getAttribute( 'rel' );
			$url = self::limit_url( $link->getAttribute( 'href' ), $url );
			if ( ! empty( $url ) ) {
				$links[ $rel ] = $url;
			}
		}

		$meta['title'] = trim( $xpath->query( '//title' )->item( 0 )->textContent );
		$meta          = self::parse_meta( $meta );
		if ( isset( $meta['og'] ) ) {
			$meta['og'] = self::parse_meta( $meta['og'] );
		}

		$video_extensions = array(
			'mp4',
			'mkv',
			'webm',
			'ogv',
			'avi',
			'm4v',
			'mpg',
		);
		$audio_extensions = array(
			'mp3',
			'ogg',
			'm4a',
			'm4b',
			'flac',
			'aac',
		);
		$urls             = array();
		foreach ( $xpath->query( '//a' ) as $link ) {
			$u         = WP_Http::make_absolute_url( $link->getAttribute( 'href' ), $url );
			$urls[]    = wp_http_validate_url( $u );
			$extension = pathinfo( wp_parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION );
			if ( in_array( $extension, $audio_extensions, true ) ) {
				$audios[] = $url;
			}
			if ( in_array( $extension, $video_extensions, true ) ) {
				$videos[] = $url;
			}
		}

		// Possibility of finding the content
		$content = apply_filters( 'parse_this_content', '', $xpath, $url );

		$audios = array_unique( $audios );
		$videos = array_unique( $videos );
		$images = array_unique( $images );
		$return = array_filter( compact( 'jsonld', 'meta', 'images', 'embeds', 'audios', 'videos', 'links', 'content' ) );
		$jf2    = self::raw_to_jf2( $return );
		if ( WP_DEBUG ) {
			$jf2['_raw'] = $return;
		}
		return $jf2;
	}
861541
public function determineAvailableLanguages(JsonDocument $jsonDocument)
    {
        $jsonDocument = $this->polyFillMultilingualFields($jsonDocument);
        return parent::determineAvailableLanguages($jsonDocument);
    }
870959
protected function addLinkedResources(Document $document, array &$json)
    {
        $name = 'linked';

        if (
            0 < count($document)
            and $$name = $this->linkedResourcesSerializer->serialize($document)
        ) {
            $json[$name] = $$name;
        }

        return $this;
    }
409732
protected function decodeJson($jsonString)
    {
        $jsonErrors = [
            \JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
            \JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
            \JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
            \JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
            \JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
        ];

        // Can we use JSON_BIGINT_AS_STRING?
        $options = (version_compare(\PHP_VERSION, '5.4.0', '>=') and ! (defined('JSON_C_VERSION') and \PHP_INT_SIZE > 4)) ? \JSON_BIGINT_AS_STRING : 0;
        $data = json_decode($jsonString, false, 512, $options);

        if (json_last_error() !== \JSON_ERROR_NONE) {
            $last = json_last_error();

            $error = 'Unknown error';

            if (isset($jsonErrors[$last])) {
                $error = $jsonErrors[$last];
            }

            throw new InputException('Unable to parse JSON data: ' . $error);
        }

        return $data;
    }
391670
protected function getJsonDocumentList()
    {
        if (!isset($this->config['library'])) {
            return json_encode(static::$apiResponseBody, JSON_PRETTY_PRINT);
        }

        if (!count($this->config['library'])) {
            return json_encode(static::$apiResponseBody, JSON_PRETTY_PRINT);
        }

        foreach (array_keys($this->config['library']) as $document) {
            static::$apiResponseBody['data'][] = [
                'document' => $document,
                'link' => Router::url([
                    'plugin' => 'Alt3/Swagger',
                    'controller' => 'Docs',
                    'action' => 'index',
                    $document
                ], true)
            ];
        }

        return json_encode(static::$apiResponseBody, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES);
    }
843311
public function getDocumentById($documentId)
    {
        /* @var $query SearchQuery */
        $query = $this->queryBuilder->newSearchQuery($documentId)->useQueryFields(QueryFields::fromString('id'))->getQuery();
        $response = $this->search->search($query, 0, 1);
        $parsedData = $response->getParsedData();
        $resultDocument = isset($parsedData->response->docs[0]) ? $parsedData->response->docs[0] : null;

        if (!$resultDocument instanceof Document) {
            throw new \UnexpectedValueException("Response did not contain a valid Document object");
        }

        return $this->searchResultBuilder->fromApacheSolrDocument($resultDocument);
    }
751523
def jsonld(client, datasets):
    """"""
    from renku.models._json import dumps
    from renku.models._jsonld import asjsonld

    data = [
        asjsonld(
            dataset,
            basedir=os.path.relpath(
                '.', start=str(dataset.__reference__.parent)
            )
        ) for dataset in datasets
    ]
    click.echo(dumps(data, indent=2))
6487
public function getDocs($format = 'array')
    {
        if ($format == 'json') {
            $filler = [];
            foreach ($this->docs as $doc) {
                $filler[] = $doc->toArray();
            }

            return json_encode($filler, true);
        }

        return $this->docs;
    }
1286345
public function parseJson($jsonString)
    {
        $stopWords = [];

        $decodedResponse = json_decode($jsonString);

        if (isset($decodedResponse->wordSet->managedList)) {
            $stopWords = (array)$decodedResponse->wordSet->managedList;
        }

        return $stopWords;
    }
1025610
public function docs($jsonFile = null)
    {
        $filePath = config('swagger-lume.paths.docs').'/'.
            (! is_null($jsonFile) ? $jsonFile : config('swagger-lume.paths.docs_json'));

        if (! File::exists($filePath)) {
            abort(404, 'Cannot find '.$filePath);
        }

        $content = File::get($filePath);

        return new Response($content, 200, ['Content-Type' => 'application/json']);
    }
111328
public function loadJSONString($jsonString)
    {
        $jsonData = json_decode($jsonString);
        foreach ($jsonData as $key => $values) {
            switch ($key) {
                case 'require':
                    foreach ($values as $require => $version) {
                        $this->addRequire($require, $version);
                    }
                    break;
                case 'require-dev':
                    foreach ($values as $require => $version) {
                        $this->addRequireDev($require, $version);
                    }
                    break;
                case 'conflict':
                    foreach ($values as $conflict => $version) {
                        $this->addConflict($conflict, $version);
                    }
                    break;
                case 'replace':
                    foreach ($values as $replace => $version) {
                        $this->addReplace($replace, $version);
                    }
                    break;
                case 'provide':
                    foreach ($values as $provide => $version) {
                        $this->addProvide($provide, $version);
                    }
                    break;
                case 'suggest':
                    foreach ($values as $suggest => $version) {
                        $this->addSuggest($suggest, $version);
                    }
                    break;
                case 'repositories':
                    foreach ($values as $value) {
                        $repository = new Repository();
                        $repository->loadJSONObject($value);
                        $this->addRepository($repository);
                    }
                    break;
                case 'scripts':
                    foreach ($values as $name => $path) {
                        if (is_array($path)) {
                            foreach ($path as $value) {
                                $this->addScript($name, $value);
                            }
                        } else {
                            $this->addScript($name, $path);
                        }
                    }
                    break;
                case 'extra':
                    $this->setExtra($values);
                    break;
                case 'config':
                    $this->setConfig($values);
                    break;
                case 'authors':
                    $this->setAuthors($values);
                    break;
                case 'name':
                    $this->setName($values);
                    break;
                case 'description':
                    $this->setDescription($values);
                    break;
                case 'type':
                    $this->setType($values);
                    break;
                case 'keywords':
                    foreach ($values as $value) {
                        $this->addKeyword($value);
                    }
                    break;
                case 'homepage':
                    $this->setHomepage($values);
                    break;
                case 'readme':
                    $this->setReadme($values);
                    break;
                case 'time':
                    $this->setTime($values);
                    break;
                case 'license':
                    $this->setLicense($values);
                    break;
                case 'support':
                    $this->getSupport()->loadJSONObject($values);
                    break;
                case 'autoload':
                    $this->getAutoload()->loadJSONObject($values);
                    break;
                case 'autoload-dev':
                    $this->getAutoloadDev()->loadJSONObject($values);
                    break;
                case 'minimum-stability':
                    $this->setMinimumStability($values);
                    break;
                case 'version':
                    $this->setVersion($values);
                    break;
            }
        }

        return $this;
    }
1074798
protected function getDocumentData($document)
    {
        if (is_array($document)) {
            $data = $document;
        } elseif ($document instanceof AbstractDocument) {
            $reflectionClass = new \ReflectionClass($document);
            $documentProperty = $reflectionClass->getParentClass()->getProperty('document');
            $documentProperty->setAccessible(true);
            $data = $documentProperty->getValue($document);
            foreach ($data as $key => &$value) {
                if ($value instanceof DocumentSerializableInterface) {
                    $value = $value->documentSerialize()->jsonSerialize();
                }
            }
        } else {
            throw new \Exception('Invalid data type, array or AbstractDocument expected');
        }

        return $data;
    }
287730
private function parseJson(string $data): stdClass
    {
        $data = json_decode($data);

        if ($data instanceof stdClass) {
            return $data;
        }

        $errorCode = json_last_error();

        if ($errorCode !== JSON_ERROR_NONE) {
            throw JsonValidationException::parseError(json_last_error_msg(), $errorCode);
        }

        throw JsonValidationException::notAcceptable(
            sprintf('Expected a JSON object, got %s', gettype($data))
        );
    }
724542
private function buildSourcePaths(SimpleXMLElement $phpDocumentor): array
    {
        $sourcePaths = [];
        $directories = $this->buildDirectories($phpDocumentor);

        foreach ($directories as $directory) {
            $sourcePaths[] = (new Dsn($directory))->getPath();
        }

        return $sourcePaths;
    }