javascript - convert string to json array - javascript

I was using s3 select to fetch selective data and display them on my front end .
I converted array of byte to buffer and then to string like below as string
let dataString = Buffer.concat(records).toString('utf8');
the result i got was string like below
{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
Now i want to convert them to json array , i got a solution like below
let dataArray = dataString.split('\n');
//remove white spaces and commas etc
dataArray = dataArray.filter(d=> d.length >2);
//change string to json
dataArray = dataArray.map(d=> JSON.parse(d));
Now the problem is that i have splitted them with new line and wont work if the json is compressed or data itself can have new line.
What is the best way to handle this situation. i want the output like below
[{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"},
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"},
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"},
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"},
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"},
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"},
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"},
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"},
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"},
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"},
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"},
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
]

#sumit
please take a look at this solution.
let dataString=`{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
let dataArray = dataString.match(/{(?:[^{}]*|(R))*}/g);
dataArray = dataArray.map(d=> JSON.parse(d));
console.log(dataArray);

Yeah, it is not a very good idea to concatenate objects into a string like that. If you don't have any other choice, however, something like that should do the trick:
const initialString = `{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
const json = `[${initialString.replace(/}\s*{/g, '},{')}]`;
const array = JSON.parse(json);

Related

how to change thousands line of number to an array in JavaScript

I got thousands lines of number
142156
108763
77236
78186
110145
126414
115436
133275
132634
......
82606
and I wanna change it to an array [142156, 108763, 108763, 77236, 78186, ....]
If I could make all these number assigned to a variable, I could choose either to use the RegExp or to convert to string first and then array.
any idea how to make it as a variable or other better suggestions?
Read as string from file then split the string at line breaks and map the resultant array of strings to number
const str = `142156
108763
77236
78186
110145
126414
115436
133275
132634`;
const arr = str.split(/\r?\n/).map(Number)
console.log(arr)
You can use following method.
const nums = document.getElementById("numbersDiv").innerHTML;
const numsToArr = nums.split('\n').map(Number)
console.log({ numsToArr } )
<div id="numbersDiv">142156
108763
77236
78186
110145
126414
115436
133275
132634</div>

JSON to JS array

JSON:
[{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}]
Is it possible to put all the distance value in their own array in JS? The formatting will be consistent as it comes from an API and is always formatted correctly.
What I've tried:
var arry = [ /* JSON noted above */ ];
alert(arry[1])
and
var arry = JSON.parse([ /* JSON noted above */ ]);
alert(arry[1])
Expected:
1
Actual:
{"CDATE":"0000-00-00","DISTANCE":"1"}
and the other gives an error.
I would like to extract just the DISTANCE value as an array of DISTANCE
I've tried JSON.parse() but I don't think this is what I am after as it hasn't worked for me.
Use .map
var data = [{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}];
var distance = data.map(el => el.DISTANCE);
console.log(distance[2]);
console.log(distance);
It is already a valid json so you do not need to use JSON.parse()

How to split into valid array

I've following object that is return from API and I want to convert them into array either in javascript or c#.
[
"1":"h1:first",
"2":".content a > img",
"3":"#content div p"
]
I've tried converting that to json object, split function etc but din't working for me.
It throws exception Uncaught SyntaxError: Unexpected token : while using split function in javascript.
You can convert it to valid JSON by replacing the square brackets with curly braces.
var data = '["1":"h1:first","2":".content a > img","3":"#content div p"]';
var json = `{ ${data.trim().slice(1, -1)} }`;
Then JSON.parse it like you had tried earlier. And if you want an array, and don't care about the actual index numbers, you can use Object.values to get the Array of values.
var data = '["1":"h1:first","2":".content a > img","3":"#content div p"]';
var json = `{ ${data.trim().slice(1, -1)} }`;
console.log(json);
var parsed = JSON.parse(json);
console.log(parsed);
var array = Object.values(parsed);
console.log(array);
I choose c# code to fix the issue instead client-side (as suggested by #rock star below).
string[] domSelectors = selectors.Replace("\"", "").Split(new string[] { "[", ",", "]" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var domSelector in domSelectors)
{
string[] arrayElements = domSelector.Split(':');
string selector = string.Join(":", arrayElements.Skip(1));
}
Hope it helps others who don't have control over API and want to fix the issue as I'd in my project!

set array as value in json format in Javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

Parse json array using javascript

I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.

Categories

Resources