Turn string from JSON array into another array in javascript - javascript

I'm trying to port the following code to use JSON files http://malamas.com/jsuc/jsuc.html
Currently i have managed to take the 'unit' and 'factor' parts of this:
property[0] = "Acceleration";
unit[0] = new Array("Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)");
factor[0] = new Array(1, .3048, 9.806650, .01, 2.54E-02);
and put them into a JSON line:
var text = '{"Accelleration": { "unit":"\\"Meter/sq.sec (m/sec^2)\\", \\"Foot/sq.sec (ft/sec^2)\\", \\"G (g)\\", \\"Galileo (gal)\\", \\"Inch/sq.sec (in/sec^2)\\"", "factor":"1, .3048, 9.806650, .01, 2.54E-02"}}'
var obj = JSON.parse(text);
Which i can have output as a string like this
"Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)"
but i want to be able to feed it into the top code by doing this:
property[0] = "Acceleration";
unit[0] = new Array(obj.Accelleration.unit);
factor[0] = new Array(obj.Accelleration.factor);
Unfortunately, when i do that, unit[0][0] brings up the same thing;
"Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)"
How can i make it so it works as an array? Thanks!

What you have in your JSON is a string that contains some representation of strings. As that representation is not JSON, you can't parse it directly (but you could by adding brackets around it to turn it into JSON).
Instead of having a string that contains strings, make it an array that contains strings. Then when you parse it, you will already have the array:
var text = '{"Accelleration": { '+
'"unit": ["Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)" ], '+
'"factor": [ 1, .3048, 9.806650, .01, 2.54E-02 ]'+
'}}'
var obj = JSON.parse(text);
Now you have your arrays, without having to do anything more than getting them from the object:
unit[0] = obj.Accelleration.unit;
factor[0] = obj.Accelleration.factor;

Related

javascript - convert string to json array

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);

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!

Double ToString keeping "en-US" format

Sounds simples - And I know it is... but i'm having issues with it and don't know why exactly..
I have a web application globalized (multilanguages).
When I click to change the language, this is my action:
public ActionResult ChangeCulture(string lang)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
var languageCookie = new HttpCookie("_language") { Value = lang, Expires = DateTime.UtcNow.AddYears(1) };
Response.Cookies.Remove("_language");
Response.SetCookie(languageCookie);
return Redirect(Request.UrlReferrer.PathAndQuery);
}
And I have a page to display some char (I'm using chart.js) and I need to bind a List<double> to a javascript array.
So this list looks like:
var list = new List<double> {144, 0, 540.23};
And I need a simples array in javascript:
var arr = [144, 0, 540.23];
Here is how I'm doing (razor):
var arr = [#string.Join(",", Model.ListWithDoubles.Select(x => Convert.ToString(x, new CultureInfo("en-US"))))]
The problem is:
When I'm using english language its works pretty. The others langues gives me integer numbers instead...
var arr = [144, 0, 540.23]; //en-US
var arr = [144, 0, 54023]; //pt-BR
var arr = [144, 0, 54023]; //it
var arr = [144, 0, 54023]; //es
Questions
Why?
How to fix?
Because in some other non en-US cultures the , and . have the exact opposite meaning and usage. If you are not displaying this data, only for chart purposes, then use CultureInfo.InvariantCulture when converting the double to string representation for the HTML. You should only convert to a culture specific string at the point you want to actually visually display that data value to the user.
var arr = [#string.Join(",", Model.ListWithDoubles.Select(x => Convert.ToString(x, CultureInfo.InvariantCulture)))]
The default format specifier for double is G so it will create output with only a decimal separator. As you want the raw number (not formatted for display) then this (CultureInfo.InvariantCulture) is what you need to pass, not the culture formatted string representation as that is for display only.
To illustrate that the code I posted works regardless of the culture of the current thread here is that code. Drop this into a console application and replace the Main method and run it. You will see that this works. Your issue lies elsewhere, not with this code.
static void Main(string[] args)
{
var cultures = new[] {"en-US", "pt-BR", "it", "es"};
var list = new List<double> {144, 0, 540.23};
Console.WriteLine("Without specifying a culture");
foreach (var culture in cultures.Select(isoCulture => new CultureInfo(isoCulture)))
{
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
Console.WriteLine("Culture: " + culture.Name);
Console.WriteLine("Not defined: " + string.Join(",", list.Select(x => Convert.ToString(x))));
Console.WriteLine("CultureInfo.InvariantCulture: " + string.Join(",", list.Select(x => Convert.ToString(x, CultureInfo.InvariantCulture))));
}
Console.ReadLine(); // stops so you can see the results
}

How to push new key/value pair into external json file? [duplicate]

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

Javascript [Object object] error in for loop while appending string

I am a novice trying to deserialize my result from an onSuccess function as :
"onResultHttpService": function (result, properties) {
var json_str = Sys.Serialization.JavaScriptSerializer.deserialize(result);
var data = [];
var categoryField = properties.PodAttributes.categoryField;
var valueField = properties.PodAttributes.valueField;
for (var i in json_str) {
var serie = new Array(json_str[i] + '.' + categoryField, json_str[i] + '.' + valueField);
data.push(serie);
}
The JSON in result looks like this:
[
{
"Text": "INDIRECT GOODS AND SERVICES",
"Spend": 577946097.51
},
{
"Text": "LOGISTICS",
"Spend": 242563225.05
}
]
As you can see i am appending the string in for loop..The reason i am doing is because the property names keep on changing therefore i cannot just write it as
var serie = new Array(json_str[i].propName, json_str[i].propValue);
I need to pass the data (array type) to bind a highchart columnchart. But the when i check the var serie it shows as
serie[0] = [object Object].Text
serie[1] = [object Object].Spend
Why do i not get the actual content getting populated inside the array?
You're getting that because json_str[i] is an object, and that's what happens when you coerce an object into a string (unless the object implements toString in a useful way, which this one clearly doesn't). You haven't shown the JSON you're deserializing...
Now that you've posted the JSON, we can see that it's an array containing two objects, each of which has a Text and Spend property. So in your loop, json_str[i].Text will refer to the Text property. If you want to retrieve that property using the name in categoryField, you can do that via json_str[i][categoryField].
I don't know what you want to end up with in serie, but if you want it to be a two-slot array where the first contains the value of the category field and the second contains the value of the spend field, then
var serie = [json_str[i][categoryField], json_str[i][valueField]];
(There's almost never a reason to use new Array, just use array literals — [...] — instead.)

Categories

Resources