Parse a JSON formatted string and convert it into an object

If not JSON tries YML.

@param   string  $data     JSON formatted string to convert
@param   array   $options  Options used by the formatter
@return   object   Data object
324835
public function stringToObject($data, array $options=[])
  {
    $data = trim($data);
    if ( substr($data, 0, 1) !== '{' && substr($data, -1, 1) !== '}' ){
      return Format::getInstance('Yaml')->stringToObject($data, $options);
    }
    
    $decoded = json_decode($data);
    
    if ( $decoded === null ){
      throw new \RuntimeException(sprintf('Error decoding JSON data: %s', json_last_error_msg()));
    }
    
    return (object)$decoded;
  }
792803
public function toJson($options = 0)
    {
        $items = array_map(function ($value)
        {
            if ($value instanceof JsonableInterface) {
                return json_decode($value->toJson(), true);
            } elseif ($value instanceof ArrayableInterface) {
                return $value->toArray();
            } else {
                return $value;
            }
        }, $this->items);

        return json_encode($items, $options);
    }
959704
public function deserialize($data, AbstractMessage $message, array $options = [])
    {
        $this->sipe('content', 'setContent', $data, $message);

        if (isset($data['meta'])) {
            if (isset($data['meta']['updated'])) {
                $message->setModificationDate(DateNormalizer::denormalize($data['meta']['updated']));
            }

            if (isset($data['meta']['creator'])) {
                $message->setAuthor($data['meta']['creator']['name']);
                //_om is set by the trait
                $creator = $this->_om->getObject($data['meta']['creator'], User::class);

                if ($creator) {
                    $message->setCreator($creator);
                }
            }
        }

        return $message;
    }
215802
public static function create(array $data, array $options = []) {
        /** @type \Titon\Model\Model $model */
        $model = new static();
        $model->fill($data);

        if ($model->save($options)) {
            return $model;
        }

        return null;
    }
484507
public function deserialize($data, BooleanQuestion $question = null, array $options = [])
    {
        if (empty($question)) {
            $question = new BooleanQuestion();
        }

        $this->deserializeChoices($question, $data['choices'], $data['solutions'], $options);

        return $question;
    }
436319
public function insert($data, $options = [])
    {
        return $this->database->createCommand()->insert($this->name, $data, $options);
    }
1304043
protected function _prepareMessage($data, array $options)
    {
        $attributes = [];

        $options += [
            'silent' => false,
            'compress' => true,
            'serializer' => extension_loaded('msgpack') ? 'msgpack' : 'json',
            'delivery_mode' => 1
        ];

        switch ($options['serializer']) {
            case 'json':
                $data = json_encode($data);
                $attributes['content_type'] = 'application/json';
                break;

            case 'text':
                $attributes['content_type'] = 'application/text';
                break;

            default:
                throw new RuntimeException('Unknown serializer: ' . $options['serializer']);
        }

        if (!empty($options['compress'])) {
            $data = gzcompress($data);
            $attributes += ['content_encoding' => 'gzip'];
        }

        if (!empty($options['delivery_mode'])) {
            $attributes['delivery_mode'] = $options['delivery_mode'];
        }

        return [$data, $attributes, $options];
    }
805221
public static function stringToStruct($data, array $options = [])
    {
        $obj = new \stdClass();

        // Parse the XML string.
        $xml = simplexml_load_string($data);

        foreach ($xml->children() as $node) {
            $obj->{$node['name']} = static::getValueFromNode($node);
        }

        return $obj;
    }
611842
public function deserialize($data, Message $message, array $options = [])
    {
        $message = $this->messageSerializer->deserialize($data, $message, $options);

        if (isset($data['subject'])) {
            $subject = $this->om->getObject($data['subject'], Subject::class);

            if (!empty($subject)) {
                $message->setSubject($subject);
            }
        }

        if (isset($data['parent'])) {
            $parent = $this->om->getRepository($this->getClass())->findOneBy(['uuid' => $data['parent']['id']]);

            if ($parent) {
                $message->setParent($parent);
            }
        }
        $this->sipe('meta.flagged', 'setFlagged', $data, $message);
        $this->sipe('meta.moderation', 'setModerated', $data, $message);

        return $message;
    }
799356
public function make($data, $options=array())
	{
		// Options
		$this->options = array_merge($this->options, $options);
		$options       = $this->options;

		// Capture output
		$out  = [];

		// @todo - Raise an exception instead ?
		// Would make more send and could be handled more gracefully
		//
		// Have any records actually been passed through ?
		if (empty($data)) {
			return $this->hasNoData($options);
		}

		// If a 'id' key has been specified use that as the table#id
		$tableId = null;

		if (!empty($options['id'])) {
			$tableId = "id='{$options['id']}'";
		}

		$out[] = "<div class=\"{$options['wrapperClass']}\">";
		$out[] = "\t<table class='{$options['containerClass']}' {$tableId}>";

		// Render headers
		if (true == $options['showHeaders']) {
			$headers = $this->extractHeaders($data);

			$out[] = "\t\t<thead>\r\t\t\t<tr class=\"{$options['headerClass']}\">";
			$count = 1;

			/**
			 * Create the <th> tag
			 */
			foreach ($headers as $index => $header)
			{
				$class = $this->getHeaderClass($header, $count);
				$count++;

				// Apply sort links to header
				if (isset($options['sort'][$header])) {

					$sortBy = $options['sort'][$header];
					$label  = $header;

					$header = $this->applyHeaderSort($label, $sortBy);
				}

				$out[] = "\t\t\t\t<th class=\"{$class}\">{$header}</th>";
			}

			$out[] = "\t\t\t</tr>\r\t\t</thead>";
		}

		$out[] = "\t\t<tbody>";

		// Render rows
		foreach ($data as $index => $row)
		{
			$rowClass = ($index % 2 == 0) ? $options['rowClass'] : $options['rowClassAlt'];

			if (isset($row['id'])) {
				$out[] = "\t\t\t<tr class='{$rowClass}' id='{$row['id']}-{$row['id']}'>";
			} else {
				$out[] = "\t\t\t<tr class='{$rowClass}'>";
			}

			foreach ($row as $field => $value) {
				$indent = "";
				if ($field == 'Title' && isset($options['type']) && $options['type'] == 'table-tree') {
					if (!empty($row['parent_id'])) {
						$indent = str_repeat($options['indent_style'], $row['depth']);
					}
				}

				if (in_array($field, $options['hiddenFields'], true)) {
					continue;
				}

				$fieldClass = $options['fieldClass'];

				if (is_array($value)) {
					//Log::info('@todo - Replace with logging interface');
					//$value = implode(',' $value);
					$value = 'Array';
				}

				$out[] = "\t\t\t\t<td class=\"{$fieldClass}\">{$value}</td>";

			}

			$out[] = "\t\t\t</tr>";
		}

		$out[] = "\t\t</tbody>";
		$out[] = "\t</table>";
		$out[] = "</div>";

		$this->output['table'] = implode(PHP_EOL, $out);

		return $this;
	}
837639
private function writeData(array $data, array $options)
    {
        $this->write(json_encode($data, isset($options['json_encoding']) ? $options['json_encoding'] : 0));
    }
1089753
public function save($data = null, array $options = []) {
        if ($data) {
            $this->data($data);
        }

        return $this->getRepository()->save($this, $options);
    }
568482
public function deserialize($data, BookReferenceConfiguration $bookReferenceConfiguration = null, array $options = [])
    {
        if (empty($bookReferenceConfiguration)) {
            $bookReferenceConfiguration = new BookReferenceConfiguration();
        }

        $this->sipe('apiKey', 'setApiKey', $data, $bookReferenceConfiguration);

        return $bookReferenceConfiguration;
    }
74805
public function json( $data = [], $status = 200, array $headers = [], $options = 0 )
	{
		if ( $data instanceof Arrayable && !$data instanceof JsonSerializable )
			$data = $data->toArray();

		return new JsonResponse( $data, $status, $headers, $options );
	}
1312033
protected function parseSet($data, $options)
    {
        if (empty($data)) {
            return [];
        }
        unset($options);
        $result = [];
        foreach ($data as $key => $val) {
            $item = $this->parseKey($key);
            if (is_array($val) && isset($val[0]) && in_array($val[0], ['$inc', '$set', '$unset', '$push', '$pushall', '$addtoset', '$pop', '$pull', '$pullall'])) {
                $result[$val[0]][$item] = $this->parseValue($val[1], $key);
            } else {
                $result['$set'][$item] = $this->parseValue($val, $key);
            }
        }
        return $result;
    }
234758
public function deserialize($data, $content = null, array $options = [])
    {
        if ('text/html' === $data['type'] || 'text/plain' === $data['type']) {
            // HTML is directly stored in the choice entity
            $content->setData($data['data']);
            $content->setResourceNode(null);
        } else {
            // Other types require a ResourceNode
            $node = $this->resourceContentSerializer->deserialize($content);

            $content->setData('');
            $content->setResourceNode($node);
        }

        return $content;
    }
1275242
public function encode($data, $options = 0) {
        $json = null;

        if ($data instanceof IArrayable) {
            $json = @json_encode($data->toArray(), $options);
        } else if ($data instanceof IJsonable) {
            $json = $data->toJson($options);
        } else if (is_array($data) || is_object($data)) {
            $json =  @json_encode($data, $options);
        } else {
            throw new InvalidDataTypeException(
                s('Can not convert data of type "%s" to json.', get_type($data))
            );
        }

        if ($json === false) {
            throw new JsonEncodeException(json_last_error_msg(), $data);
        }

        return $json;
    }