Laravel read json from database - json

I'm trying to read and output a json from database. I insert a json using something like this:
$widget->settings = json_encode($input->get('settings'));
Then when I read I try with:
$settings = json_decode($response->settings);
However I get an escaped string and not a valid json. This is what I got:
"settings":"{\"url\":\"http:\\\/\\\/www.google.com\"}"
But I was expecting something like:
"settings":{"url":"http:\/\/www.google.com"}
[EDIT]
I've tried also to add this to my model:
public function getSettingsAttribute()
{
return (array)json_decode($this->settings);
}
But I got error:
Undefined property: Widget::$settings

Using this solve the problem:
public function getSettingsAttribute($value)
{
return json_decode($value);
}

you can use this with the success text:
return response()->json(array("notification" => "success", "data" => json_decode($yourdata->info)));

Related

Reading JSON file with different datatypes

I am trying to read a JSON file that contains following data
"{\"studentData\":[{\"Name\":\"Graham\",\"aggregate\":\"86\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"69\",\"sub2\":\"97\",\"sub3\":\"90\"}]},{\"Name\":\"Finley\",\"aggregate\":\"96\",\"regular\":\"false\",\"percentages\":[{\"sub1\":\"95\",\"sub2\":\"91\",\"sub3\":\"73\"}]},{\"Name\":\"Carrillo\",\"aggregate\":\"93\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"90\",\"sub2\":\"84\",\"sub3\":\"80\"}]},{\"Name\":\"Crosby\",\"aggregate\":\"68\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"63\",\"sub2\":\"92\",\"sub3\":\"77\"}]},{\"Name\":\"Small\",\"aggregate\":\"88\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"65\",\"sub2\":\"80\",\"sub3\":\"81\"}]}]}"
I have following code so far
const data = require("./testdata.json");
/*Explore the JSON file and return required JSON data*/
console.log(data)
when I run the code, I see the output in console
But how do I refer to each item in the data
e.g. Name, Regular
When I try to access using below code,
console.log(data.studentData.Name)
I get error
console.log(data.studentData.Name)
^
TypeError: Cannot read property 'Name' of undefined
data.studentData is an array so you need to loop through each value.
With forEach for example:
data.studentData.forEach((individualStudentData) => {
console.log(individualStudentData.Name);
//Do your thing (:
});
Or:
for (let individualStudentData of data.studentData)
a function like .map(() => { ... }
etc. ;)
It looks like data.studentData is actually a JSON Array. So if you wanted to log every name, you'd need to do
const data = require("./testdata.json");
data.studentData.forEach( student => console.log(student.Name));

Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid JSON

I am not sure whether my function is wrong, which should send data to the server, or the function on the server is wrong.
I looked up similar questions but the solution I adopted to my problem did not work.
My function looks like this:
postData(number){
let array = JSON.stringify(this.locArr);
return this.http.post<any>(this.url, array)
.subscribe(),
error => console.log("Error: ", error)
}
JSON which is send:
[
{
"id":222,
"name":"Lars",
"sLA":37
},
{
"id":223,
"name":"Sim",
"sLA":12
}
]
All parameters like token etc. are received by the server function but the array I wrote above is null, although it is valid json.
I wonder why this error is occuring.
Any advice is appreciated
The local array will be converted into JSON automatically by Angular, you need not stringify or parse it.
postData(number){
this.http.post<any>(this.url, this.locArr)
.subscribe((data)=>{
//code after receiving data from server
},
error => console.log("Error: ", error))
}
I believe you are using httpClientModule so then there is no need of tyou need't JSON.stringify remove this step JSON.stringify(this.locArr);
Also you need to send it as json object {} not json array []
postData($locArr){ // pass the array to the service function
let data = { data : $locArr}; // note that you have to post it as json object {} not []
return this.http.post<any>(this.url,data);
}

Json object in Camel exchange header not correctly converting to string

So I'm trying to split a json array with some metadata and append the metadata to each object in the array:
{
"#version":"1",
"metadata":{"key1":"value1","key2":"value2"},
"messages":[{"msg":{...}},{"msg":{...}}, ... ]
}
to
{
"type":"msg",
"data":{
"#version":"1",
"metadata":{"key1":"value1","key2":"value2"},
"msg":{...}
}
}
I have the following Camel route which almost works:
from("direct:kafkaMsg")
.routeId("rKafkaMsg")
.log(DEBUG, "JSON: ${body}")
.setHeader("#version").jsonpath("$.#version")
.setHeader("metadata").jsonpathWriteAsString("$.metadata") // not writing as string
.split().jsonpathWriteAsString("$.messages..msg")
.setHeader("msgId", jsonpath("$.msgNo"))
.setHeader("kafka.KEY", simple("${header.msgId}"))
.setBody(simple("{\"type\":\"msg\","
+ "\"data\":{\"#version\":\"${header.#version}\",\"metadata\":${header.metadata},"
+ "\"msg\":${body}}}"))
.log(DEBUG, "body: ${body}")
.log(INFO, "msgPush: writing msg to kafka - msgId: ${header.msgId}")
.setProperty(Exchange.CHARSET_NAME, constant("UTF-8"))
.to("kafka:sometopic?partitioner=" + DefaultPartitioner.class.getName())
.end();
But the Json I actually get like this is:
{
"type":"msg",
"data":{
"#version":"1",
"metadata":{key1="value1",key2="value2"}, // wrong. This looks like mapToString
"msg":{...}
}
}
When I had .split().jsonpath("$.messages..msg") before, the 'msg' object was also wrongly formatted in the output but jsonpathWriteAsString() helped in this case. I also tried jsonpath("$.metadata", String.class) but it did not help.
Does anybody know how to fix this? Thanks.
I solved this using a workaround involving a Processor:
.split().jsonpath("$.messages..msg")
.setHeader("msgId", jsonpath("$.msgNo"))
.setHeader("kafka.KEY", simple("${header.msgId}"))
// Processor instead of setBody()
.process(exchange -> {
JsonObject data = new JsonObject();
data.put("#version", exchange.getIn().getHeader("#version"));
data.put("metadata", exchange.getIn().getHeader("metadata"));
data.put("msg", exchange.getIn().getBody());
JsonObject body = new JsonObject();
body.put("type", "msg");
body.put("data", data);
exchange.getOut().setBody(body.toJson());
exchange.getOut().setHeaders(exchange.getIn().getHeaders());
})
I prefer this solution anyway because I don't have to write part of the json string myself.

Best way to parse single json string response

I want to parse a json response like that :
{
"code": "#546545"
}
from an angular 2 service. There are two ways that I know of:
Use an interface
export interface ProductId{
code: string;
}
Since json is a string use: angular.fromJson(code)
I think 1 is an overkill for a single string along with what I know what is the best way for something so simple?
Either JSON.parse(string) or
angular.fromJson(string)
which is just
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
The interface would help you, I don't think it's an overkill. But you still need to parse the string anyway.

Json manipulation TypeScript Angular 2

I come from a Python Background and recently started programming using TypeScript and Angular2. I want to know how to obtain keys from a JSON object using TypeScript.
I have a response like so:
response.text()
I pass this object to a function
removeMetaData (my_data: string){
//(Various manipulation)...etc
}
i have read that I can call a json() method instead of text(). If I do that, what is the type I should use for my_data?
Then,
If my JSON looks like this:
{
"count": 100,
"next_page": "http://www.test.com/users/?page=2",
"prev_page": "http://www.test.com/users/?page=3",
"results":[
{
"username": "johnny"
},
Etc....
]
How do I parse that?
I've read I might have to use an interface but I don't understand how.
In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. That is exactly what I'm trying to achieve within a component.
Thank you.
ADDITION
list() {
this.requestService.get(this.api_path)
.subscribe(
response => this.populate(response.json()),
error => this.response = error.text()
)
}
populate(payload: object) {
this.count = payload.count;
this.next = payload.next;
this.previous = payload.previous;
*payload.results => this.users = payload.results;******
}
Declare an interface which will be used as value object.
export interface IPage
{
count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}
var my_data:IPage;
Now assign parsed json value to my_data and access all the properties with '.' operator i.e. my_data.count, my_data.results.
Feel free to throw any question.
If I do that, what is the type I should use for my_data?
Its just a javascript object.
As an example if you json looks like:
{
"foo": {
"bar": "bas"
}
}
Then in the parsed json (in variable someObj) the value someObj.foo.bar would be bas 🌹