On submission I am storing data in the Json format in the database.
But when I am fetching the database the Json is fetched in the string format as the datatype is set as TEXT.
I want to retrieve some of the Json objects like only companyName from this Json.
{
deleted: false,
Id: 1,
Request: "{"companyName":"ABCD","address":"sd"}",
Uuid: "7f000101-4fdf-160d-814f-dfa60dc80000",
isDeleted: false,
modifiedAt: 1442566841000,
status: 4
}
But when I am using {{info.Request}} the whole Request object is fetched and I only want companyName. How to do it?
The best solution is to store the data correctly on the database and fetch it as a full JSON object, so then you don't have to parse it with Angular or whatever software you will use to render.
If you still can't do that, then from the Front End side (not recommended):
Convert the string to JSON on the controller or another place:
$scope.parseStringToJSON = function(value) {
return JSON.parse(value);
};
Now use the object on the view:
<p>{{parseStringToJSON(info.Request).companyName}}</p>
Related
I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}
I need to be able to PUT a JSON data from POSTMAN, with no fixed format, store it in database(in MYSQL preferably with datatype: JSON) and then send a GET request to get the same value back. The data can be uniquely identified by an id that I'll be sending as a path variable.
I cannot define an entity class as the JSON will have no fixed format. How do I proceed?
#PutMapping("/sample/{sampleNo}")
public ResponseEntity<Object> addSampleData(
#ApiParam("Sampleto PUT") #PathVariable Long sampleNo, #RequestBody String sampleBody) {
if (sampleBody!= null) {
sampleService.save(new Sample(sampleNo, sampleBody));
return new ResponseEntity<>(HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
Not sure how to proceed with the "save" functionality so that the data is stored as a JSON object, because even if I've used datatype JSON n mySQL, GET returns a string with "\".
{
"sampleNo": 1,
"sampleData": "{\"sample\": \"test\", \"sampleNo\": \"20\"}"
}
Example: PUT request body
{
"field1": "test",
"field2": 20
}
GET response body expected
{
"field1": "test",
"field2": 20
}
P.S: I don't need to process the data, so it doesn't matter how I store it, I just need to be able to GET it back in the same format(JSON) it arrived(in the PUT req).
sampleData is returned as JSON String, so it is reasonable to include escape sequence \":
This is a valid JSON String:
String json = "{\"sample\": \"test\", \"sampleNo\": \"20\"}";
This does not compile:
String invalidJson = "{"sample": "test", "sampleNo": "20"}";
Solution:
In order to have the expected response, you have to map your MySQL JSON column into an Object.
There are several ways to achieve this, take a look at a solution here. It maps JSON column into a Map<String, Object>.
If I log the full data from an Angular client I get
object { type: "message", target: {_}, errorCode: undefiend,
errorMessage: undefined, data: "{\"data\":[\"124",\"611\"]}",
lastEventId: ""}
I want to grab the {\"data\":[\"124",\"611\"]} part to send it as json to a client. Using JSON.parse(data.data) though gives me
data: "{\"data\":[\"124",\"611\"]}", lastEventId: ""}
Is it possible to just grab the "{\"data\":[\"124",\"611\"]}" since otherwise the client has problems with the deserialization.
Let's say you have your initial string in myobject_string.
Then, you extract the JSON to a Javascript object with: const myobject = JSON.parse(myobject_string).
Then, the data you are looking for is in myobject.data.
Look here for more example code on JSON.parse.
I am persisting a JSON object to MongoDB here is relevant snippet:
Viewed: [
-{
ViewedID: "8992ade400a"
Dockey: "3323aba3233"
PID: "32399a"
actionsTaken: "email|direct message|report seeker"
viewDate: "01-APR-2014"
MessageSent: "true"
-Message: [
-{
MessageID: "123aca323"
Delivered: "True"
Opened: "True"
ClickThroughRate: "NotBad"
MessageDate: "02-APR-2014"
-Response: [
-{
ResponseId: "a323a9da"
ResponseDate: "23-APR-2014"
}
]
}
Here is how I am setting the JSON on my persisting object:
trackingData.setEventdata((DBObject)JSON.parse(tracker.getEventData().toString()));
where tracker.getEventData() returns ObjectNode when I persist the DBObject to mongo I see the dates such "viewDate" : "01-APR-2014" and "ResponseDate" : "23-APR-2014" as Strings.
I need these attributes to be converted to type date so I may query against these dates. Is there anyway to specify that these be handled as date objects either before or after parsing that JSON to DBObject?
Cheers,
Will
The com.mongodb.util.JSON.parse method supports Extended JSON format, so if the JSON was actually formatted that way then this would automatically be cast as a date.
But since it isn't then you would either need to implement a custom parser that handles the "date" elements in your JSON or otherwise just manipulate the BSON before sending it on to MongoDB.
The simplest way is just to manipulate, with something like as shown in this example:
try {
DBObject content = (DBObject)com.mongodb.util.JSON.parse("{ \"date\": \"01-APR-2014\" }");
System.out.println(content);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
content.put("date",sdf.parse((String) content.get("date")));
System.out.println(content);
} catch (ParseException e) {
e.printStackTrace();
}
So after processing the .parse() you can basically do that date conversion for each relevant date field in your source. Also keep in mind that the data is going to be stored with dates as "UTC/GMT", so make sure that the Timezone you are getting from the source is correctly represented.
So my issue is this.
Using backbone to save something in a MYSQL Database.
When I call this.model.save() I am getting a very weird issue.
The model will save the JSON response as an object and will not update the new values instead.
So my attributes in development tools will look something like this.
attributes: Object
0: Object
ID: "4"
Name: "TEST"
Title: "MEOW"
Stuff: "1"
When: "2013-02-14 22:17:14"
The 0 should not be there. I did confirm that the json object is valid so I know that is not the issue here.
It looks like your JSON response is actually an array with a single element, not an object.
The property 0 is created when Backbone calls model.set(response), which in turn copies all keys of the response object to the attributes hash. If an array is passed to set, this is what happens.
You should fix your server to respond with a raw object ({...}) instead of an array ([{...}]). If you're not able to change the server behaviour, you can override Model.parse to unwrap the response on the client:
var Model = Backbone.Model.extend({
parse: function(response) {
return _.isArray(response) ? response[0] : response;
}
});