mpneuried
2/11/2013 - 9:08 AM

Multiple replace of keys inside a object or JSON. *Useful for replacing id's with new id's.*

Multiple replace of keys inside a object or JSON.

Useful for replacing id's with new id's.

class JSONreplace
	
	###
	## _jsonreplacemap
	
	`_jsonreplacemap( _json, map )`
	
	Replace the values of a key inside of a json string.
	
	@param { String | Object } _json A Stringfied JSON or a object witch will be stringfied. 
	@param { Object } map A map object witch contains the key to replace with an array pair to replace or an array of pairs to replace. E.g. `{ key1: [ 1,2 ], key2: [ [ "a", "b" ], [ "x", "y" ] ] }`
	
	@return { String | Object } The corrected JSON-string or if you passed an object a parced object. **Attension** you will get a copy of the object and loose the reference.
	
	@api public

	###
	_jsonreplacemap: ( _json, map )=>
		# check for the type and do a stringify if necessary
		asString = true
		if not _.isString( _json )
			asString = false
			_json = JSON.stringify( _json )
		
		# loop throug the map
		for key, vals of map
			[ valOrig, valNew ] = vals
			# loop throug multiple pairs or run the replace
			if _.isArray( valOrig )
				for pair in vals when pair.length >= 2
					_json = @_jsonreplace( _json, key, pair[ 0 ], pair[ 1 ] )
			else
				_json = @_jsonreplace( _json, key, valOrig, valNew )
		
		# return as string or object depending on the input
		if asString
			_json
		else
			JSON.parse( _json )

	###
	## _jsonreplace
	
	`_jsonreplace( _sjson, key, valOrig, valNew )`
	
	Replace the values of a key inside a json string
	
	@param { String } _sjson The current json string 
	@param { String } key The key to replace
	@param { Number | String } valOrig The value to replace with the new value
	@param { Number | String } valNew The new value to replace the old 
	
	@return { String } The replaced string 
	
	@api private
	###
	_jsonreplace: ( _sjson, key, valOrig, valNew )=>
		# create the regex and check for string, number or boolean
		_sKey = "\"#{ key }\":"
		if _.isString( valOrig )
			_search = _sKey + '"' + valOrig + '"'
		else
			_search = _sKey + valOrig
		
		# run the replace
		_sjson = _sjson.replace new RegExp( _search, "g" ), ( _found, idx )->	
			if _.isString( valOrig )
				_sKey + '"' + valNew + '"'
			else
				_sKey + valNew
		_sjson