Convert array to JSON list

        nan values are converted to string 'nan', inf values to 'inf'.
486066
def to_json(value, **kwargs):
        
        def _recurse_list(val):
            if val and isinstance(val[0], list):
                return [_recurse_list(v) for v in val]
            return [str(v) if np.isnan(v) or np.isinf(v) else v for v in val]
        return _recurse_list(value.tolist())
691090
@JsonValue
	public Object toJsonValue() {
		if (s != null)
			return s;
		if (n != null)
			return n;
		return null;
	}
609100
def create_string_array(self, key, value):
        
        data = None
        if key is not None and value is not None:
            if isinstance(value, (list)):
                data = self.db.create(key.strip(), json.dumps(value))
            else:
                # used to save raw value with embedded variables
                data = self.db.create(key.strip(), value)
        else:
            self.tcex.log.warning(u'The key or value field was None.')
        return data
1328340
function arrayToStr(key, value) {
  if (isString(value) || isNumber(value)) return `${key}=${value}`;
  if (isString(value[0])) return `${key}=${value.join(':')}`;
  if (value && value.toString) return `${key}=${value.toString()}`;

  return value.map(val => arrayToStr(key, val));
}
486824
def tojson(val, indent=None):
    '''
    
    '''
    options = {'ensure_ascii': True}
    if indent is not None:
        options['indent'] = indent
    return (
        salt.utils.json.dumps(
            val, **options
        ).replace('<', '\\u003c')
         .replace('>', '\\u003e')
         .replace('&', '\\u0026')
         .replace("'", '\\u0027')
    )
1361122
function toJSON() {
    function filter(obj) {
      return Object.keys(obj)
        .filter(function(key) {
          return typeof obj[key] !== 'function' && key[0] !== '_';
        })
        .reduce(function(clone, key) {
          clone[key] = typeof obj[key] !== 'object' ?
            obj[key] : filter(obj[key]);
          return clone;
        }, Array.isArray(obj) ? [] : {});
    }
    return JSON.stringify(filter(obj));
  }
306927
def _convert_data(self, data, data_type, num_recs, num_values, num_elems):
        '''
        
        '''

        if (data_type == 51 or data_type == 52):
            return [data[i:i+num_elems].decode('utf-8') for i in
                    range(0, num_recs*num_values*num_elems, num_elems)]
        else:
            tofrom = self._convert_option()
            dt_string = self._convert_type(data_type)
            form = tofrom + str(num_recs*num_values*num_elems) + dt_string
            value_len = CDF._type_size(data_type, num_elems)
            return list(struct.unpack_from(form,
                                           data[0:num_recs*num_values*value_len]))
1110933
def decode_array(values):
    
    out = []
    for val in values:
        try:
            out.append(val.decode('utf8'))
        except AttributeError:
            out.append(val)
    return out
929447
def jsonify(obj):  # pylint: disable=too-many-return-statements
    
    # Call the `to_json` method if available and add metadata.
    if hasattr(obj, 'to_json'):
        d = obj.to_json()
        _push_metadata(d, obj)
        return jsonify(d)

    # If we have a numpy array, convert it to a list.
    if isinstance(obj, np.ndarray):
        return obj.tolist()

    # If we have NumPy datatypes, convert them to native types.
    if isinstance(obj, (np.int32, np.int64)):
        return int(obj)
    if isinstance(obj, np.float64):
        return float(obj)

    # Recurse over dictionaries.
    if isinstance(obj, dict):
        return _jsonify_dict(obj)

    # Recurse over object dictionaries.
    if hasattr(obj, '__dict__'):
        return _jsonify_dict(obj.__dict__)

    # Recurse over lists and tuples.
    if isinstance(obj, (list, tuple)):
        return [jsonify(item) for item in obj]

    # Otherwise, give up and hope it's serializable.
    return obj
308201
public static String toJson(Object value) {
        if (value instanceof String) {
            return '"' + (String) value + '"';
        } else if (value instanceof Collection) {
            return "[" + toJsonCollection((Collection) value) + "]";
        } else {
            throw new IllegalArgumentException("Unable to convert " + value + " to JSON");
        }
    }
470187
def to_json(self, incl_uniqueid=False):
        
        def _parse(k, v):
            
            if k=='value':
                if isinstance(self._value, nparray.ndarray):
                    if self._value.unit is not None and hasattr(self, 'default_unit'):
                        v = self._value.to(self.default_unit).to_dict()
                    else:
                        v = self._value.to_dict()
                if isinstance(v, u.Quantity):
                    v = self.get_value() # force to be in default units
                if isinstance(v, np.ndarray):
                    v = v.tolist()
                return v
            elif k=='limits':
                return [vi.value if hasattr(vi, 'value') else vi for vi in v]
            elif v is None:
                return v
            elif isinstance(v, str):
                return v
            elif isinstance(v, dict):
                return v
            elif isinstance(v, float) or isinstance(v, int) or isinstance(v, list):
                return v
            elif _is_unit(v):
                return str(v.to_string())
            else:
                try:
                    return str(v)
                except:
                    raise NotImplementedError("could not parse {} of '{}' to json".format(k, self.uniquetwig))

        return {k: _parse(k, v) for k,v in self.to_dict().items() if (v is not None and k not in ['twig', 'uniquetwig', 'quantity'] and (k!='uniqueid' or incl_uniqueid or self.qualifier=='detached_job'))}
56183
def values_to_array(input_values):
    '''
    
    '''
    if type(input_values)==tuple:
        values = np.array(input_values).reshape(-1,1)
    elif type(input_values) == np.ndarray:
        values = np.atleast_2d(input_values)
    elif type(input_values)==int or type(input_values)==float or type(np.int64):
        values = np.atleast_2d(np.array(input_values))
    else:
        print('Type to transform not recognized')
    return values
1081884
public static String makeJSONArrayString(Object[] values) {
        // Since they won't change during a run, compute the JSON value for the
        // summary data fields (an array where all field names are wrapped in quotes
        StringBuilder buf = new StringBuilder();
        int numVals = values.length;

        buf.append("[");
        for (int i = 0; i < numVals; i++) {
            buf.append(QUOTE);
            buf.append(values[i].toString());
            buf.append(QUOTE);
            if (i < numVals - 1) {
                buf.append(COMMA);
            }
        }
        buf.append("]");

        return buf.toString();
    }
832510
function (vValue) {
			var sJSON;

			if (typeof vValue !== "function") {
				try {
					sJSON = Basics.toJSON(vValue);
					// undefined --> undefined
					// null, NaN, Infinity --> "null"
					// all are correctly handled by String
					if (sJSON !== undefined && sJSON !== "null") {
						return sJSON;
					}
				} catch (e) {
					// "converting circular structure to JSON"
				}
			}
			return String(vValue);
		}
971114
private JSONArray toJsonStringArray(Collection<? extends Object> collection) {

        if (null != collection) {
            JSONArray array = new JSONArray();
            for (Object o : collection) {
                array.put("" + o);
            }
            return array;
        } else {
            return null;
        }
    }
1224863
void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
            final boolean includeNullValuedFields, final int depth, final int indentWidth,
            final StringBuilder buf) {
        final boolean prettyPrint = indentWidth > 0;
        final int n = items.size();
        int numDisplayedFields;
        if (includeNullValuedFields) {
            numDisplayedFields = n;
        } else {
            numDisplayedFields = 0;
            for (final Entry<String, Object> item : items) {
                if (item.getValue() != null) {
                    numDisplayedFields++;
                }
            }
        }
        if (objectId == null && numDisplayedFields == 0) {
            buf.append("{}");
        } else {
            buf.append(prettyPrint ? "{\n" : "{");
            if (objectId != null) {
                // id will be non-null if this object does not have an @Id field, but was referenced by
                // another object (need to include ID_TAG)
                if (prettyPrint) {
                    JSONUtils.indent(depth + 1, indentWidth, buf);
                }
                buf.append('"');
                buf.append(JSONUtils.ID_KEY);
                buf.append(prettyPrint ? "\": " : "\":");
                JSONSerializer.jsonValToJSONString(objectId, jsonReferenceToId, includeNullValuedFields, depth + 1,
                        indentWidth, buf);
                if (numDisplayedFields > 0) {
                    buf.append(',');
                }
                if (prettyPrint) {
                    buf.append('\n');
                }
            }
            for (int i = 0, j = 0; i < n; i++) {
                final Entry<String, Object> item = items.get(i);
                final Object val = item.getValue();
                if (val != null || includeNullValuedFields) {
                    final String key = item.getKey();
                    if (key == null) {
                        // Keys must be quoted, so the unquoted null value cannot be a key
                        // (Should not happen -- JSONParser.parseJSONObject checks for null keys)
                        throw new IllegalArgumentException("Cannot serialize JSON object with null key");
                    }
                    if (prettyPrint) {
                        JSONUtils.indent(depth + 1, indentWidth, buf);
                    }
                    buf.append('"');
                    JSONUtils.escapeJSONString(key, buf);
                    buf.append(prettyPrint ? "\": " : "\":");
                    JSONSerializer.jsonValToJSONString(val, jsonReferenceToId, includeNullValuedFields, depth + 1,
                            indentWidth, buf);
                    if (++j < numDisplayedFields) {
                        buf.append(',');
                    }
                    if (prettyPrint) {
                        buf.append('\n');
                    }
                }
            }
            if (prettyPrint) {
                JSONUtils.indent(depth, indentWidth, buf);
            }
            buf.append('}');
        }
    }
924189
def toJson(self, data=None, pretty=False):
        """"""
        if data==None: data = self.attrs
        data = self.flatten(data) # don't send objects as str in json
        #if pretty:
        ret = json.dumps(data, indent=4, sort_keys=True)
        #self.inflate() # restore objects from json str data
        return ret