I'm using a data-set given to me and I'm trying to parse (Using Node) the JSON objects returned to me,
Turns out they are all using single quotations, and from my research JSON uses double.
Example of a JSON object I get returned!
{
'cast_id': 16,
'character': 'Alexander Haig',
'credit_id': '52fe43c59251416c7501d72d',
'gender': 2,
'id': 6280,
'name': 'Powers Boothe',
'order': 2,
'profile_path': '/3nNL6AvMAYq0BmHKM79RnRZVq3i.jpg'
},
I've been using str.replace() to sort the objects out before JSON.parse() which was fine untill I found objects like this one
{
'cast_id': 26,
'character': '"Jack Jones"',
'credit_id': '52fe43c59251416c7501d751',
'gender': 2,
'id': 6840,
'name': 'Larry Hagman',
'order': 16,
'profile_path': '/40PVsGp5Wp5kbUhAefLHqjqbarc.jpg'
},
Notice the 'character': '"Jack Jones"', This has been causing me all types of issues!
I there a library that will help parse this all for me?
Am I missing something?
FYI:
I can't access each record as the JSON objects aren't stored separately instead, as a long string including up to 60 JSON objects.
I currently have a function that helps parse the data:
function formatJSON(cast) {
cast = cast.replace(/(\w) "(\w)/g, "$1 *$2");
cast = cast.replace(/(\w)" /g, "$1* ");
cast = cast.replace(/': '/g, '": "');
cast = cast.replace(/', '/g, '", "' );
cast = cast.replace(/'},/g, '"},');
cast = cast.replace(/': /g, '": ');
cast = cast.replace(/, '/g, ', "');
cast = cast.replace(/{'/g, '{"');
cast = cast.replace(/: None}/g, ': "None"}');
cast = cast.replace(/'}/g, '"}');
return cast;
}
Update
The data reportedly extracts nicely in python as a dictionary using ast.literal_eval()
By default, you don't need to replace a string which is wrapped by double quotes with the same string contains single quote. There is no difference between 'Jack Jones' and "Jack Jones" since all of them are string.
In your case, you're trying to replace something like this example:
var str = '\'Jack Jones\''.replace(/'/g, '"');
console.log('\'' + str + '\'');
So, if you want to wrap all of properties names and values by double quotes, you can use JSON.stringify and JSON.parse like this:
var cast = {
'cast_id': 16,
'character': 'Alexander Haig',
'credit_id': '52fe43c59251416c7501d72d',
'gender': 2,
'id': 6280,
'name': 'Powers Boothe',
'order': 2,
'profile_path': '/3nNL6AvMAYq0BmHKM79RnRZVq3i.jpg'
};
cast = JSON.stringify(cast);
cast = JSON.parse(cast);
console.log(cast);
Related
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));
I am getting a SQL RequestError while trying to insert a string into a SQL Server table. The string is com.redacted.redacted.redacted. I think that the periods in the string are throwing some kind of red flag that it is a reference to some property of an object, or something along those lines. I am using the mssql node module for the request.
let myObj = {
Date: '2015-06-22',
PackageName: 'com.redacted.redacted.redacted'
}
let date = myObj['Date']
let pName = myObj['PackageName']
request.query('insert into myTable ([DATE],[PackageName]) values (' + date + ',' + pName + '))
I have not found anything online about trying to avoid using the dot notation, but I have found some of the opposite, trying to get into the notation. I also looked but there is no RegExp keyword to keep a period as literally a period.
The exact Error:
REQ ERROR
{ [RequestError: The multi-part identifier "com.redacted.redacted.redacted" could not be bound.]
name: 'RequestError',
message: 'The multi-part identifier "com.redacted.redacted.redacted" could not be bound.',
code: 'EREQUEST',
number: 4104,
lineNumber: 1,
state: 1,
class: 16,
serverName: 'REDACTED',
procName: '' }
can you use double quotes to wrap the sql
request.query("insert into myTable ([DATE],[PackageName]) values ('" + date + "','" + pName + "')")
Just to be safe, you may want replace any single quotes in pName with TWO single quotes
I'm new to RegExp and to JS in general (Coming from Python), so this might be an easy question:
I'm trying to code an algebraic calculator in Javascript that receives an algebraic equation as a string, e.g.,
string = 'x^2 + 30x -12 = 4x^2 - 12x + 30';
The algorithm is already able to break the string in a single list, with all values on the right side multiplied by -1 so I can equate it all to 0, however, one of the steps to solve the equation involves creating a hashtable/dictionary, having the variable as key.
The string above results in a list eq:
eq = ['x^2', '+30x', '-12', '-4x^2', '+12x', '-30'];
I'm currently planning on iterating through this list, and using RegExp to identify both variables and the respective multiplier, so I can create a hashTable/Dictionary that will allow me to simplify the equation, such as this one:
hashTable = {
'x^2': [1, -4],
'x': [30, 12],
' ': [-12]
}
I plan on using some kind of for loop to iter through the array, and applying a match on each string to get the values I need, but I'm quite frankly, stumped.
I have already used RegExp to separate the string into the individual parts of the equation and to remove eventual spaces, but I can't imagine a way to separate -4 from x^2 in '-4x^2'.
You can try this
(-?\d+)x\^\d+.
When you execute match function :
var res = "-4x^2".match(/(-?\d+)x\^\d+/)
You will get res as an array : [ "-4x^2", "-4" ]
You have your '-4' in res[1].
By adding another group on the second \d+ (numeric char), you can retrieve the x power.
var res = "-4x^2".match(/(-?\d+)x\^(\d+)/) //res = [ "-4x^2", "-4", "2" ]
Hope it helps
If you know that the LHS of the hashtable is going to be at the end of the string. Lets say '4x', x is at the end or '-4x^2' where x^2 is at end, then we can get the number of the expression:
var exp = '-4x^2'
exp.split('x^2')[0] // will return -4
I hope this is what you were looking for.
function splitTerm(term) {
var regex = /([+-]?)([0-9]*)?([a-z](\^[0-9]+)?)?/
var match = regex.exec(term);
return {
constant: parseInt((match[1] || '') + (match[2] || 1)),
variable: match[3]
}
}
splitTerm('x^2'); // => {constant: 1, variable: "x^2"}
splitTerm('+30x'); // => {constant: 30, variable: "x"}
splitTerm('-12'); // => {constant: -12, variable: undefined}
Additionally, these tool may help you analyze and understand regular expressions:
https://regexper.com/
https://regex101.com/
http://rick.measham.id.au/paste/explain.pl
I have the following object
{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
}
loaded from a text file abc.txt in my local directory in the server.
I want to convert this into an array object. I tried doing
var string = "{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
}"
var array = JSON.parse("[" + string + "]");
alert(array);
Nothing happens unfortunately. Help appreciated !
You can use "eval" to accomplish what you are attempting.
var s = '{value: 20, color:"#878BB6" },' +
'{value : 40, color : "#4ACAB4"}';
var arr = eval('[' + s + ']');
alert(arr[0].value);
Also, in order for JSON.parse to parse it the string needs to be valid JSON. So you'll need to have quotes around the object property names. Like the following:
var s = '{"value": 20, "color":"#878BB6" },' +
'{"value": 40, "color": "#4ACAB4"}';
var arr2 = JSON.parse('[' + s + ']');
alert(arr2[1].value);
Although it would be better to modify the process for generating the text file to contain valid JSON if you can. Then you could use jQuery or some other method of just loading the JSON from the file directly.
I'm trying to construct a String in JS that can be passed into JSON as an with a very particular format. Desired result is a string of the following form:
["PNG","350x150","127 KB"]
Where PNG correspond to a particular image's type, where 350x150 is the image's dimensions and where 127 KB is the image's size. Each of these threee values are string variables:
var imgType = getImageType(); // Returns "PNG"
var imgDim = getImageDim(); // Returns "350x150"
var imgSize = getImageSize(); // Returns "127 KB"
var imgDescription = '["' + imgType + '","' + imgDim + '","' + imgSize + '"]';
// Sanity check
alert(imgDescription);
iVO.images[thisImage] = {
"fizz":"buzz",
"imgDesc":imgDescription,
"foo":"bar"
}
alert(JSON.stringify(iVO));
The first alert (on the imgDescription variable) prints:
["PNG","350x150","127 KB"]
So far, so good. However, the minute we pass it to the iVO construct and stringify the resultant JSON, it generates the following output (after I pretty print format it):
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":"[\"PNG\",\"350x150\",\"127 KB\"]",
"foo":"bar"
}
}
}
All of my double quotes (") have been escaped (\")!!! Also, the value for imgDesc is enclosed in double-quotes, which is not what we want (see desired JSON below):
When I send this JSON back to the server its causing the server to choke.
Not sure what is going on here but I've tried several other suggestions, including replacing my double-quotes with '\x22' instances which didn't help.
Any ideas as to what would fix this to get the desired result from JSON.stringify(iVO)? Ultimately that's the only thing that matters, that the we end up sending the following to the server:
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":["PNG","350x150","127 KB"],
"foo":"bar"
}
}
}
No escaped double-quotes, and the value for imgDesc is not double-quoted. Thanks in advance!
Why don't you just put imgDescription as regular array
var imgDescription = [imgType , imgDim, imgSize];
Stringify should take care of what you are trying to do, otherwise you are passing imgDescription as a string and stringify would escape the quotes.
e.g.
var imgType = "PNG";
var imgDim = "350x150";
var imgSize = "127 KB";
var d = {
"fizz":"buzz",
"imgDesc":[imgType , imgDim, imgSize],
"foo":"bar"
}
console.log(JSON.stringify(d));
Output:
{"fizz":"buzz","imgDesc":["PNG","350x150","127 KB"],"foo":"bar"}