Converting string containing array of arrays into JSON object - javascript

I have an API that returns me a string that contains an array of arrays. The arrays contains strings, like here:
"[['cat','mouse'],['duck','fish'],['lion','zebra']]"
and I want to convert it into a JSON object.
I've tried JSON.parse, but it's giving me an error
Blockquote
[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kaliningrad)','+03:0
^
SyntaxError: Unexpected token '
The string that im trying to turn into an object is this one:
"[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kaliningrad)','+03:00 (Europe/Kaliningrad)'],['-01:00 (Etc/GMT+1)','-01:00 (Etc/GMT+1)'],['AKST (America/Anchorage)','AKST (America/Anchorage)'],['ART (America/Argentina/Buenos_Aires)','ART (America/Argentina/Buenos_Aires)'],['AST (America/Puerto_Rico)','AST (America/Puerto_Rico)'],['AST (Asia/Baghdad)','AST (Asia/Baghdad)'],['AST (Atlantic/Bermuda)','AST (Atlantic/Bermuda)'],['BRT (America/Sao_Paulo)','BRT (America/Sao_Paulo)'],['CET (CET)','CET (CET)'],['CET (Europe/Amsterdam)','CET (Europe/Amsterdam)'],['CET (Europe/Brussels)','CET (Europe/Brussels)'],['CET (Europe/Budapest)','CET (Europe/Budapest)'],['CET (Europe/Madrid)','CET (Europe/Madrid)'],['CET (Europe/Oslo)','CET (Europe/Oslo)'],['CET (Europe/Paris)','CET (Europe/Paris)'],['CET (Europe/Prague)','CET (Europe/Prague)'],['CET (Europe/Vienna)','CET (Europe/Vienna)'],['CET (Europe/Warsaw)','CET (Europe/Warsaw)'],['CET (Europe/Zurich)','CET (Europe/Zurich)'],['CLST (America/Santiago)','CLST (America/Santiago)'],['COT (America/Bogota)','COT (America/Bogota)'],['CST (America/Chicago)','CST (America/Chicago)'],['CST (America/Costa_Rica)','CST (America/Costa_Rica)'],['CST (America/Mexico_City)','CST (America/Mexico_City)'],['CST (Asia/Shanghai)','CST (Asia/Shanghai)'],['CST (Asia/Taipei)','CST (Asia/Taipei)'],['CST (Australia/Adelaide)','CST (Australia/Adelaide)'],['EAT (Africa/Nairobi)','EAT (Africa/Nairobi)'],['EET (EET)','EET (EET)'],['EET (Europe/Istanbul)','EET (Europe/Istanbul)'],['EET (Europe/Kiev)','EET (Europe/Kiev)'],['EST (America/Indiana/Indianapolis)','EST (America/Indiana/Indianapolis)'],['EST (America/New_York)','EST (America/New_York)'],['EST (Australia/Brisbane)','EST (Australia/Brisbane)'],['EST (Australia/Melbourne)','EST (Australia/Melbourne)'],['EST (Australia/Sydney)','EST (Australia/Sydney)'],['GMT (Europe/Dublin)','GMT (Europe/Dublin)'],['GMT (Europe/London)','GMT (Europe/London)'],['GST (Asia/Dubai)','GST (Asia/Dubai)'],['HKT (Asia/Hong_Kong)','HKT (Asia/Hong_Kong)'],['HST (Pacific/Honolulu)','HST (Pacific/Honolulu)'],['ICT (Asia/Bangkok)','ICT (Asia/Bangkok)'],['IST (Asia/Jerusalem)','IST (Asia/Jerusalem)'],['IST (Asia/Kolkata)','IST (Asia/Kolkata)'],['JST (Asia/Tokyo)','JST (Asia/Tokyo)'],['KST (Asia/Seoul)','KST (Asia/Seoul)'],['MSK (Europe/Moscow)','MSK (Europe/Moscow)'],['MST (America/Denver)','MST (America/Denver)'],['MST (America/Phoenix)','MST (America/Phoenix)'],['MST (MST)','MST (MST)'],['MYT (Asia/Kuala_Lumpur)','MYT (Asia/Kuala_Lumpur)'],['NZDT (Pacific/Auckland)','NZDT (Pacific/Auckland)'],['PET (America/Lima)','PET (America/Lima)'],['PHT (Asia/Manila)','PHT (Asia/Manila)'],['PST (America/Los_Angeles)','PST (America/Los_Angeles)'],['PYST (America/Asuncion)','PYST (America/Asuncion)'],['SAST (Africa/Johannesburg)','SAST (Africa/Johannesburg)'],['SGT (Asia/Singapore)','SGT (Asia/Singapore)'],['TJT (Asia/Dushanbe)','TJT (Asia/Dushanbe)'],['UTC (UTC)','UTC (UTC)'],['VET (America/Caracas)','VET (America/Caracas)'],['WET (Europe/Lisbon)','WET (Europe/Lisbon)'],['WST (Australia/Perth)','WST (Australia/Perth)']]"

This is not valid JSON. You have to replace the ' characters with ".

Your JSON is invalid as mentioned in the first answer but this is a quick fix.
Say you have:
a = "[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kalini..
Then replace the ' with ":
a = a.replace(/'/g, '"');
Then parse it to JSON:
a = jQuery.parseJSON(a)
Then you have a valid JSON, try console.table(a) to see your valid json!

Related

Convert string with '=' to JSON format

I am trying to convert a string i receive back from an API into a JSON object in Angular.
The issue is that the string is not normalized to be parsed into JSON easily.
This is the string im working with:
"{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
When trying to do JSON.parse(myStr) it throws an error due to invalid string format.
Is there an easy way to convert the listed string into a more correct JSON format, getting rid of the '=' and replacing them with ':' instead.
There is more to it than just .replace(/['"]+/g, ''), as even with that the string is not ready to be turned into JSON yet.
Hoping someone more versed in Javascript knows a trick i dont.
You just need to manipulate the string before parsing it remove unecessary string that can cause error to the object like "{" and "}" and split it by "," example is in below.
var obj = {}, str = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
str.split(",").forEach((st, i) => {
pair = st.split("=")
if(pair.length > 1) {
obj[pair[0].replace("{",'').replace("}", '').trim()] = pair[1]
} else {
obj[i] = pair
}
})
console.log(obj)
As commenters have posted, unless you control the API or at least have documentation that output will always follow a specific format, then you are limited in what you can do. With your current example, however you can trim off the extraneous bits to get the actual data... (remove braces, split on comma, split on equals) to get your key:value pairs... then build a javascript object from scratch with the data... if you need json string at that point can just JSON.stringify()
var initialString = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
var trimmedString = initialString.substr(1, initialString.length - 2);
var pairArray = trimmedString.split(',');
var objArray = [];
pairArray.forEach(pair => {
var elementArray = pair.split('=');
var obj = {
key: elementArray[0].trim(),
value: elementArray[1].trim()
};
objArray.push(obj);
});
var returnObj = {};
objArray.forEach(element => {
returnObj[element.key] = element.value;
});
console.log(JSON.stringify(returnObj));

Javascript- convert content in textbox to key value pair

I have a textbox which accepts user defined key value pairs like:
{'Apple':'Red', 'Lemon':'Green'} and i want it to be converted to an array of key value pair.
I have code:
var color= document.getElementById('txtColor').value;
The problem is i get it just as a string if i try: color['Apple'] it shows undefined; whereas i expect 'Red'. How can i do the conversion so that i get something like:
var color={'Apple':'Red', 'Lemon':'Green'}
and get value 'Red' on color['Apple'].
Thanks in advance.
I have a similar usecase. You have to JSON.parse() the value.
var obj = JSON.parse(document.getElementById('txtColor').value.replace(/'/g, '"'));
console.log(obj['Apple']);
<textarea id="txtColor">{'Apple':'Red', 'Lemon':'Green'}</textarea>
I assume following
let color = document.getElementById('txtColor').value; // This line returns {'Apple':'Red', 'Lemon':'Green'}
If I'm correct you can do following
try {
// Here you can write logic for format json ex. Convert single quotes to double quotes
// This may help to convert well formatted json string https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
let colorJson = JSON.parse(color);
console.log(colorJson["Apple"]) // This will return your expected value.
} catch(e) {
console.log('Invalid json format')
}
var color = document.getElementById('txtColor').value;
//JSON.stringify will validate the JSON string
var jsonValidString = JSON.stringify(eval("(" + color + ")"));
//If JSON string is valid then we can conver string to JSON object
var JSONObj = JSON.parse(jsonValidString);
//We can use JSON.KeyName or JSON["KeyName"] both way you can get value
console.log(JSONObj.Apple, " --- ", JSONObj["Apple"]);
console.log(JSONObj.Lemon, " --- ", JSONObj["Lemon"]);
<input id="txtColor" value="{'Apple':'Red', 'Lemon':'Green'}" type="text" />

Convert json single node value STRING to OBJECT using Angularjs

How can i convert a json node VALUE STRING to OBJECT using Angularjs. I am getting response from server values as string format. Here a node FCLASS is Name and ' "[{ .... }]" ' its value but value is string instead of array, need to remove first (") and last (") character and (/) all slashes inside value for converting array and object ' [{ ... }] '.
JSON:
{"FARE":[{
"ARRV_DATE": "2016-06-25",
"ARRV_TIME": "14:15",
"FCLASS ": "[{\"TYPE\":\"UPPER\",\"CL\":\"M2\"},{\"TYPE\":\"UPPER\",\"CL\":\"Y2\"},{\"TYPE\":\"LOWER\",\"CL\":\"S2\"}]",
"SEAT": 0,
},
{
"ARRV_DATE": "2016-06-25",
"ARRV_TIME": "16:20",
"FCLASS ": "[{\"TYPE\":\"UPPER\",\"CL\":\"J2\"},{\"TYPE\":\"UPPER\",\"CL\":\"C2\"},{\"TYPE\":\"LOWER\",\"CL\":\"D2\"}]",
"SEAT": 0,
},
{
"ARRV_DATE": "2016-06-25",
"ARRV_TIME": "19:10",
"FCLASS ": "[{\"TYPE\":\"UPPER\",\"CL\":\"H2\"},{\"TYPE\":\"UPPER\",\"CL\":\"C2\"},{\"TYPE\":\"LOWER\",\"CL\":\"O2\"}]",
"SEAT": 0,
}
}]
ng-repeat isn't looping this value because its requires only OBJECT.
HTML(angularjs)
.........
<div class="col-sm-2" ng-repeat="n in f.FCLASS">
<div>{{n.TYPE}}-{{n.CL}}</div>
</div>
.........
Any ideas. How to solve this? Thanks
Try using JSON.parse to parse the json string.
try this,
$scope.f.FCLASS=JSON.parse(YOUR_OBJECT.FCLASS);
I suggest first stringify value with
JSON.stringify(YOUR_OBJECT.FCLASS);
then convert to JSON object with
JSON.parse(YOUR_OBJECT.FCLASS);
Because stringifying will convert to string regardless of object OR array. It will perform as expected even if there will be Array in object value.
Regards

JSON Serialization error with simplejson

I have the following code:
data = {'services': [u'iTunes'],
'orders': [u'TestOrder', u'Test_April_Titles_iTunes'],
'providers': ''}
return HttpResponse(simplejson.dumps(data))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
178. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /reports/change_dropdown/
Exception Value: [u'iTunes'] is not JSON serializable
What do I need to do to serialize this dictionary with a list inside it?
The problem is that itunes is a non-JSON compatible type.
To solve provide default type to convert non-JSON compatible types when serializing:
simplejson.dumps(data, default=str))
or even:
def handler(val):
if isinstance(val, unicode)
return str(val)
else:
return val
simplejson.dumps(data, default=handler))
The advantage of the second option is you can handle sets (e.g., convert to list), dates (e.g., convert to int timetstamp), etc.
Converting from unicode to str worked here:
data['services'] = [str(item) for item in data['services']]
data['orders'] = [str(item) for item in data['orders']]
data['providers'] = [str(item) for item in data['providers']]

How to parse unicode character to xml format standard

I have some problem such as. When I call webservice and Webservice return Dataset and output as following:
"\u003cNewDataSet\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e81\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e81\u003c/Column1\u003e\r\n \u003cszDescription\u003eAKL Airside sdda\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e0\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e82\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e82\u003c/Column1\u003e\r\n \u003cszDescription\u003eAKL Landsite\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e0\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e85\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e85\u003c/Column1\u003e\r\n \u003cszDescription\u003eAKL Arrival\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e0\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e886\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e886\u003c/Column1\u003e\r\n \u003cszDescription\u003e886-PreOrder\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e-1\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n\u003c/NewDataSet\u003e"
I want it output XML format.
If this is the actual character data you have got, then you need to do some string replacements. Assuming the string is the value of a variable s, then you can do this:
s = s.replace(/\\u003c/gi,"<").replace(/\\u003e/gi,">").replace(/\\r\\n/g, "\n");

Categories

Resources