Remove data and timestamp in JSON - javascript

A function call in nodejs returns a JSON object which is of below format:
**2018-01-24T19:03:37.736Z 47306e51-0139-11e8-9cbb-2d7164fff26e**
{
GroupId: "sg-sdfdg",
GroupName: "launch-wizard-2",
IpPermissions: [
{
IpProtocol: "-1",
IpRanges: [
{
CidrIp: "0.0.0.0/0"
}
]
}
]
}
Timestamp gets embedded in the array object which is causing some issue while passing this object as input to another function. I want to remove the timestamp from this output.

If that is the actual JSON, you can use JS:
.replace(/ *\*[^)]*\* */g, "");
This will remove everything between the stars('*').

Related

How to parse an string into more workable key-values?

So I have the following response:
{
"errors": [
{
"errorKey": "ERROR_NO_DELIVERY_OPTIONS",
"errorParameters": "[{\"errorMessage\":\"ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW\",\"partNumbers\":[\"19308033\",\"19114798\"]},{\"errorMessage\":\"Pickup At Seller not available for these orderItemIds\",\"orderItemIds\":[\"10315031\",\"10315032\"],\"availableShipModeId\":\"13201\"}]",
"errorMessage": "ERROR_NO_DELIVERY_OPTIONS",
"errorCode": "ERROR_NO_DELIVERY_OPTIONS"
}
]
}
Unfortunately, I'm not sure how to work with the value of "errorParameters" since it just a string and not a simple key-value like the others. How would I extract all the information so I can work with it. A co-woker mentioned parsing it but not sure what he meant by that and how. Below is a more readable value. I'm working with javascript.
[
{
"errorMessage": "ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW",
"partNumbers":
[
19308033,
19114798
]
},
{
"errorMessage": "No Shipmodes Available for these orderItemsIds",
"orderItemIds": [
10315031,
10315032
]
}
]
You will need to use JSON.parse to transform JSON strings into a JS Object.
You'll need to do this in your code. I.E.
data.errors.forEach(e => console.log(JSON.parse(e.errorParameters)))
You can use just JSON.parse() function, which changes string JSON representation into a JavaScript object.
const parsedErrorParameters = JSON.parse(data.errorParameters);
console.log(parsedErrorParameters[0].errorMessage); // ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

How to convert a single string to object

I have multiple objects and trying to do a condition based on the object name. I am trying to check the name of the object based on the variable, which is a string. Is there any way to convert a single value string to object
const showHtml= {
one: {
code: "<DIV>",
pos: "1"
},
two: {
code: "<Body>",
pos: "2"
}
}
const showcss= {
one: {
code: "text-align",
pos: "1"
},
two: {
code: "float",
pos: "2"
}
}
I have a string variable (showHTML and showcss). I want to return the code based on the variable, so i am doing
let uVariable = localstorage.getItem("ftype")
console.log(uVariable.one.code)
I should get
<DIV>
but as i am passing the string, I can't get the object name, is there any way to convert the uVariable into object?
Thank you
You want JSON.parse here. Localstorage only stores strings. In your case, the code would look something like this:
let uVariable = JSON.parse(localstorage.getItem("ftype"))
console.log(uVariable.one.code)
String => object, use JSON.parse
Object => string, use JSON.stringify
please read this code, might help you
so initially we have variable showHtml which contains json data.
you should try this
JSON.parse(localStorage.getItem('showHtml')).one.code
and you can try jsfiddle:
https://jsfiddle.net/dupinderdhiman/f5wz7Lv1/2/
for more explanation read below:
var showHtml= {
one: {
code: "<DIV>",
pos: "1"
},
two: {
code: "<Body>",
pos: "2"
}
}
var showcss= {
one: {
code: "text-align",
pos: "1"
},
two: {
code: "float",
pos: "2"
}
}
localStorage.setItem('showcss', JSON.stringify(showcss));
localStorage.setItem('showHtml', JSON.stringify(showHtml));
alert('showHtml '+JSON.parse(localStorage.getItem('showHtml')).one.code);
alert('showCss '+JSON.parse(localStorage.getItem('showcss')).one.code)

Remove the parent element from JSON reply

I have a route used for AJAX calls. It gets items from a DB and returns a JSON array.
I'm using:
return reply({
myArray
}).code(200);
Everything works but my output in the browser is:
{
"myArray":[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
}
But what I need is:
{
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
}
Very basically, I need to get rid the "myArray" parent element and leave just the array there. It looks like a simple task but I can't find documentation or samples anywhere.
Thanks,
Marco
This:
{
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
}
is invalid JSON notation. Within curly braces, you should have key-value pairs where keys are strings and values are valid JSON values (strings, numbers, booleans, null, arrays, or objects).
Perhaps what you expect is just the array:
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
which is valid JSON. In this case, you may simply send it to your reply function:
return reply(myArray).code(200);
For more info on JSON notation, see the article on MDN and play with JSON.stringify to develop better intuition on when the JSON you see is valid or not.

JSON parsing with multiple data

Jsonlint display that this JSON object is valid:
[{"obj":{"markers":"[{\"k\":47.040182144806664,\"B\":0.52734375},{\"k\":50.90303283111257,\"B\":10.37109375},{\"k\":52.53627304145945,\"B\":-1.7578125},{\"k\":41.77131167976406,\"B\":-6.591796875}]","path":"[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]"}}]
I'm trying to access to markers with the k, B and path elements but it's always set to undefined. Here is my code:
try {
var jsonData = JSON.parse(myJson);
console.log(jsonData.obj[0].markers[0].k);
}
catch (e) {
console.error("Parsing error:", e);
}
Can someone tell me how to access to the element of my JSON object properly? Thanks for the help.
Something must have gone wrong in creating this string. Yes, it's valid JSON, but it has a different format than you think, because you escape control characters like " and [, ].
Try this string instead:
[
{
"obj":{
"markers":[
{
"k":47.040182144806664,
"B":0.52734375
},
{
"k":50.90303283111257,
"B":10.37109375
},
{
"k":52.53627304145945,
"B":-1.7578125
},
{
"k":41.77131167976406,
"B":-6.591796875
}
],
"path":[
[
47.040182144806664,
0.52734375
],
[
50.90303283111257,
10.37109375
],
[
52.53627304145945,
-1.7578125
],
[
41.77131167976406,
-6.591796875
]
]
}
}
]
as opposed to your string:
[
{
"obj":{
"markers":"[{\"k\":47.040182144806664,\"B\":0.52734375},{\"k\":50.90303283111257,\"B\":10.37109375},{\"k\":52.53627304145945,\"B\":-1.7578125},{\"k\":41.77131167976406,\"B\":-6.591796875}]",
"path":"[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]"
}
}
]
You have two issues from what I can tell:
One, yes it is valid Json but the marker and path object values are enclosed in string quotes:
"markers":"[{\"k\":47.040182144806664,\"B\":0.52734375},{\"k\":50.90303283111257,\"B\":10.37109375},{\"k\":52.53627304145945,\"B\":-1.7578125},{\"k\":41.77131167976406,\"B\":-6.591796875}]",
"path":"[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]"
what you rather want is:
"markers":[{"k":47.040182144806664,"B":0.52734375},{"k":50.90303283111257,"B":10.37109375},{"k":52.53627304145945,"B":-1.7578125},{"k":41.77131167976406,"B":-6.591796875}],
"path":[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]
But given the above, also not escape the k and b object names for markers \"k\" should be "k":
So the completed edited JSON would look like this:
[{"obj":{"markers":[{"k":47.040182144806664,"B":0.52734375},{"k":50.90303283111257,"B":10.37109375},{"k":52.53627304145945,"B":-1.7578125},{"k":41.77131167976406,"B":-6.591796875}],"path":[[47.040182144806664,0.52734375],[50.90303283111257,10.37109375],[52.53627304145945,-1.7578125],[41.77131167976406,-6.591796875]]}}]

Parsing a JSON object-within-an-object in javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

Categories

Resources