Remove multiple square brackets using replace() - javascript - javascript

I have a response from the server that is like this:
users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
It's a string not an array like it appear, since I need an array to work on, how I can remove the square backets and then the commas to obtain a normal array?
I've tried in this way:
var data = ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
data.replace('[', '').replace(']', '').split(',');
but chaining two .replace() functions and a split() isn't the best solution. Can anyone halp me?

In your example data is an array.
However, if data was a string you would convert it to an array like this:
var arr = JSON.parse(data);

In short,
Here you have provided data in normal string formate not in JSON string formate
var data = 'users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]'
var squareBracketData = data.substr(data.indexOf("["))
var array = JSON.parse(squareBracketData)
console.log(array)
Some personal advice, Try to send JSON stringify data from the
server so it will make your life easy
Example:
var users =["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
// Stringify data
var data = JSON.stringify({users})
console.log("Data")
console.log(data)
// retrieve data from string
var parsedData = JSON.parse(data)
var parsedUsers = parsedData.users
console.log("parsedUsers")
console.log(parsedUsers)

Related

How to retrieve value from json of one array and one int literal in javascript

I am passing data back to java script through a rest api. The rest API return data in the following below mentioned structure.I am confused what format of json is it and how can i iterate on the array inside and get the int value individually.
The format of my response is like :
{"searchOrder":[
{"location":"10","trackingId":"656"},
{"location":"34","trackingId":"324"},....],
"count":100}
i want searchOrder as array of json to display in table and count to show total row.How can i get them?
Just iterate over the array and extract the values
// Turn the JSON into a JS object (maybe in your XHR handler)
var data = JSON.parse(jsonString); // jsonString could be responseText from XHR
var arrayOfTrackingIdValues = data.searchOrder.map(function (value) {
return value.trackingId;
});
JavaScript provide built-in function JSON.parse() to convert the string into a JavaScript object and drive/iterate the each element based on type obj/array
var obj = JSON.parse(text);

How To Parse A String Of Concatenated JSON In Browser?

I'm using Socket.IO to move data to the browser. The data sent is a stream of JSON objects, and when it arrives at the browser, it becomes one large string of JSON. The problem is, this JSON can't be parsed by JSON.parse() because it's not "real" JSON.
The data structure can be arbitrary so a RegEx might not do the trick. And this current setup is only temporary. Eventually this stream of JSON will be pre-processed server-side so a stream will not need to be sent to the browser, so I'd like to keep the AJAX/Socket.IO setup I have right now instead of switching over to a JSON stream parser like OboeJS.
What can I do to parse this string of concatenated JSON?
For clarity, the JSON will look like this:
{"a":"A"}{"b":"B"}{"c":"C"}
And I'm trying to parse it in such a way that I can access them like:
console.log(Object.a) //A
console.log(Object.b) //B
console.log(Object.c) //C
In your particular case, you could use Array.prototype.reduce to merge all JSON objects into one:
var unstructuredJson = '{"a":"A"}{"b":"B"}{"c":"C"}';
var jsonArray = "[" + unstructuredJson.split("}{").join("},{") + "]";
var objectArray = JSON.parse(jsonArray);
var result = objectArray.reduce(function(result, item) {
Object.keys(item).forEach(function(propertyName) {
result[propertyName] = item[propertyName];
});
return result;
}, {});
document.body.textContent = JSON.stringify(result);
OP said in some comment:
[...] Each JSON might have nested data like {{}{}}{}{}{}
Then, above approach is broken on this case.
My two cents is that you should put some separator character when you stream these JSON objects and life will be easier: you'll be able to split parent objects easily and you'll just need to change split("}{") with the whole separator.
I suggest you that you use some character that will never happen as part of any property value. You can find a control character on this Wikipedia article: Control character
If each substring is valid JSON but the concatenated part isn't, you can turn the string into a valid array literal and use JSON.parse, then you can process each object using Array methods, e.g. forEach:
var s = '{"a":"A"}{"b":"B"}{"c":"C"}';
var obj = JSON.parse('[' + s.replace(/}{/g,'},{') + ']').forEach(function (obj) {
document.write(JSON.stringify(obj) + '<br>');
});
Or if you want it as a single object:
var s = '{"a":"A"}{"b":"B"}{"c":"C"}';
var obj = JSON.parse(s.replace(/}{/g,','));
document.write(JSON.stringify(obj));
You can use JsonParser to parse concatenated json objects:
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory(mapper);
JsonParser parser = factory.createParser(YourJsonString);
List<YourObject> YourObjectList = new ArrayList<>();
Iterator<YourObject> iterator = parser.readValuesAs(YourObject.class);
while(iterator.hasNext()) {
YourObject yourObject = iterator.next();
loginSignalsList.add(yourObject);
}
Split the large string {a:'A'}{b:'B'}{c:'C'} and parse them individually

Trying to convert multi level javascript array to json, with json2 script

I am using the following script to help me convert javascript arrays to json strings: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
How come this works:
var data = [];
data[1] = [];
data[1].push('some info');
data[1].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
And this does not (returns a blank):
var data = [];
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
I want to convert multi-dimensional javascript arrays, but it seems I cannot use stringify() if I name my array keys?
JSON arrays are integer-indexed only.
You can change your first line to use {} as in http://jsfiddle.net/5YXNk/, which is the best you can do here.
Check the array syntax at http://json.org/ -- note arrays contain values only, which will be implicitly indexed by non-negative integers. That's just the way it is.
There is no such thing as an associative array in Javascript. You're going to have to use an object if you want to use string "keys".

Parse object to JSON

I have some web services that receive JSON data send by jquery method.
But I need to edit the object before send this data. Is there any way to parse a JSON object to a simple object in javascript, modify it and then parse it again to JSON. or maybe update this JSON object without parse it?
To go from a JSON string to a JavaScript object: JSON.parse, or $.parseJSON if you're using jQuery and concerned about compatibility with older browsers.
To go from a JavaScript object to a JSON string: JSON.stringify.
If I've already do this var myData = JSON.stringify({ oJson:{data1 :1}}); and then I want to update that information setting data1 = 2, what is the best way to do this?
var myData = JSON.stringify({ oJson:{data1 :1}});
// later...
parsedData = JSON.parse(myData);
parsedData.oJson.data1 = 2;
myData = JSON.stringify(parsedData);
Even better though, if you save a reference to the object before stringifying it, you don't have to parse the JSON at all:
var obj = { oJson:{data1 :1}};
var myData = JSON.stringify(obj);
// later...
obj.oJson.data1 = 2;
myData = JSON.stringify(obj);
var parsed = JSON.parse('{"a": 1}');
parsed.b = 2;
var string = JSON.stringify(parsed);
//string is: '{"a":1,"b":2}'
I think something like the following should work...
//Convert your JSON object into a JavaScript object
var myObject = JSON.parse(json);
//You can then manipulate the JavaScript object like any other
myObject.SomeValue = "new";
//Then you can convert back to a JSON formatted string
json = JSON.stringify(myObject);
As JSON is an JavaScript object you can simply manipulate it with JavaScript.
You could do something like this to get a javascript object:
var jsObject = JSON.parse(jsonString);
Then you could modify jsObject and turn it back into a JSON string with JSON.stringify.
This page has more information on it.

javascript split and JSON.parse

I want to parse array in JSON format using javascript. I have written following code.
var data = "abc, xyz, pqr";
var data_array = data.split(',');
var data_parsed = JSON.parse(data_array);
alert(data_parsed);
It gives me the error of JSON.parse
I have no idea how to resolve this javascript error.
You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:
var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);
and if you want to convert this array to a JSON string you could do this:
var json = JSON.stringify(data_array);
alert(json);
That's because "abc, xyz, pqr" isn't valid JSON. Plus, JSON.parse() is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.
This is actually a convenient short cut to json processing if you only need a smaller set of variables.
PHP:
return $var1 .','. $var2 .',some_string_value.';
Javascript:
var myReturnArray = returnValue.split(',');

Categories

Resources