Esempio n. 1
0
func (parser *Parser) parseObject(parent *value.JSONValue) error {
	parent.ObjectValue = make(map[string]value.JSONValue)

	firstToken, err := parser.tokenizer.NextToken()
	if err != nil {
		return err
	}
	if !firstToken.IsEqualTo(token.NewTokenBeginObject()) {
		return fmt.Errorf("JSON Object must start wit '{'")
	}

	for {
		nextToken, err := parser.tokenizer.PeekToken(0)
		if err != nil {
			return err
		}
		// End Of Object.
		if nextToken.IsEqualTo(token.NewTokenEndObject()) {
			parser.tokenizer.NextToken()
			break
		}
		// String Token must be key of object.
		if nextToken.IsSameKindTo(token.NewTokenString()) {
			parser.tokenizer.NextToken()

			mustbeSeparator, err := parser.tokenizer.NextToken()
			if err != nil {
				return err
			}
			if !mustbeSeparator.IsEqualTo(token.NewTokenSeparator()) {
				return fmt.Errorf("Object KeyValue Separator not found, %#v", mustbeSeparator)
			}

			currentValue := value.NewJSONValue()
			err = parser.parseValue(&currentValue)
			if err != nil {
				return err
			}
			parent.ObjectValue[nextToken.Value] = currentValue

			// If comma exists after value of object,
			// continuous token must be string which is key of the object too.
			maybeComma, err := parser.tokenizer.PeekToken(0)
			if err == nil && maybeComma.IsEqualTo(token.NewTokenComma()) {
				parser.tokenizer.NextToken()
				continue
			}
			break
		}
		return fmt.Errorf("Invalid JSON. Object is wrong")
	}
	return nil
}
Esempio n. 2
0
// Parse parses JSON.
func (parser *Parser) Parse() (value.JSONValue, error) {
	firstToken, err := parser.tokenizer.PeekToken(0)
	if err != nil {
		return value.NewJSONValue(), err
	}
	if firstToken.IsEqualTo(token.NewTokenBeginObject()) {
		parent := value.NewJSONValue()
		err := parser.parseObject(&parent)
		if err != nil {
			return value.NewJSONValue(), err
		}
		return parent, nil
	}
	if firstToken.IsEqualTo(token.NewTokenBeginArray()) {
		parent := value.NewJSONValue()
		err := parser.parseArray(&parent)
		if err != nil {
			return value.NewJSONValue(), err
		}
		return parent, nil
	}
	return value.NewJSONValue(), fmt.Errorf("Invalid JSON")
}