How parse JSON data in Codeigniter 3 - json

In my project, using Codeigniter 3, I have a controller that get a JSON object in response from an API call, I'm trying to parse the JSON object but I'm not able to figure out to the access to each data.
The JSON object is the following:
{
"ok":true,
"result":
{
"message_id":9,
"sender_chat":
{
"id":-11234567899,
"title":"Sandbox",
"username":"JustDummyUsername",
"type":"channel"
},
"chat":
{
"id":-11234156789,
"title":"Sandbox",
"username":"JustDummyUsername",
"type":"channel"},
"date":1629538111,
"text":"Lorem ipsum dummy text",
"entities":
[
{
"offset":0,
"length":26,
"type":"bold"
},
{
"offset":112,
"length":22,
"type":"text_link",
"url":"xxxxxxxxxx"
}
]
}
}
}
I try, for example, the following code to get the message_id value
$json = $this->get_json_data();
$message_id = $json->result->message_id;
or
$json = $this->get_json_data();
$message_id = $json[0]->result->message_id;
but in both cases I get an error
Trying to get property 'result' of non-object
What's wrong?
Thanks a lot for any feedback.
EDIT: Silly me...I forgot json_decode().
Fixed

Fixed. Silly me. I forgot to json_decore the returned data

Related

how to use entiy mapping this data (like json but not )

I have a problem recently.
springboot receive request, but strange!
how to use entity mapping this data below
This strange data:
a=
{
b=
{
b1=null,
b2=1,
b3=null,
b4=null,
b5=null
},
c={
c1=null,
c2=1,
c3=nfsaf
},
ds=
[
{
d1=dsdsadad,
d2=null,
d3=null
},
{...}
]
}
I try use jackson or gson to convert it,but error.
If there is no good way,i finally use regular expression to catch!
that`s all,Ignore these,Ignore these,Ignore these,Ignore these
very grateful to you for your help!

Best Schema for a Data List in JSON for RestFul API to use in Angular

I've been wondering for some days what kind of scheme would be more appropriate to use a data list in json in a web application.
I'm developing a REST Web Application, and im using Angular for front end, i should order, filter and print these data list also in xml ...
For you what scheme is better and why?
1) {
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
}
2) {
"datas": [{
"data": { "first":"","second":""},
"data": { "first":"","second":""},
"data": { "first":"","second":""}
}]
}
3) [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
Thanks so much.
The first and third notations are quite similar because the third notation is included in your first.
So the question is "Should I return my datas as an array or should I return an object with a property that contain the array ?
It will depend on either you want to have more information alongside your datas or not.
For exemple, if your API might return an error, you will want to manage it from the front end.
In case of error, the JSON will looks like this :
{
"datas": null,
"error": "An error occured because of some reasons..."
}
At the opposite, if everything goes well and your API actually return the results, it will looks like this :
{
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
],
"error": null
}
Then your front end can use the error property to manage errors sent from the API.
var result = getDatas(); // Load datas from the API
if(result.error){
// Handle the error, display a message to the user, ...
} else {
doSomething(result.datas); // Use your datas
}
If you don't need to have extra properties like error then you can stick with the third schema.
The second notation is invalid. The datas array will contain only one object which will have one property named data. In this case data is a property that is defined multiple times so the object in the array will contain only the last occurence:
var result = {
"datas": [{
"data": { "first":"a","second":"b"},
"data": { "first":"c","second":"d"},
"data": { "first":"e","second":"f"}
}]
}
console.log("Content of result.datas[0].data : ")
console.log(result.datas[0].data)
Obviously the first option would be easy to use. Once you will access datas it'll give you an array. Any operation (filter, sort, print) on that array will be easy in comparison to anything else. Everywhere you just need to pass datas not datas.data.

Reading json file in node.js

This must be something really silly. After spending the last few hours, I am here for help.
I have a users.json file
{
"Test_Session": {
"test_SessionID": [
{
"$": {
"id": "1"
},
"test_type": [
"1"
],
"Test_IDtest": [
"1"
],
"DataURL": [
"data1"
]
}
]
}
}
I try to read DataURL by
var jsonData = require('./users.json');
var test = JSON.stringify(jsonData)
console.log(test.Test_Session.test_SessionID.DataURL);
In console, I get "Can't read property test_SessionID of undefined".
What's going on?
Your main issue is that test_SessionID is an array, so when you try to access DataUrl, it will be undefined. You need to select the index of the test_SessionID object you want to read from. Try this:
console.log(test.Test_Session.test_SessionID[0].DataURL);
Also, you don't need to JSON.stringify anything, Node automatically reads the file in as JSON, so just doing
var jsonData = require('./users.json');
console.log(jsonData.Test_Session.test_SessionID[0].DataURL);
should work fine.
Node is already interpreting the JSON, try the following:
var test = require('./users.json');
console.log(test.Test_Session.test_SessionID[0].DataURL);

Get JSON in POST in kemal

What I want is a POST request in kemal where the body has a certain number of keys/values that I want to access and then an arbitrary JSON Object that I just want to stringify and pass on and later parse back to JSON.
My problem is that I apparently can't get the types right.
Think of a potential JSON body like this:
{
"endpoint": "http://example.com",
"interval": 500,
"payload": {
"something": "else",
"more": {
"embedded": 1
}
}
}
Now what I've been trying to do is the following:
require "kemal"
post "/schedule" do |env|
endpoint = env.params.json["endpoint"].as(String)
interval = env.params.json["interval"].as(Int64)
payload = String.from_json(env.params.json["payload"].as(JSON::Any))
# ... move things along
env.response.content_type = "application/json"
{ id: id }.to_json
end
Kemal.run
Now apparently what I seem to be getting when accessing "payload" is something of type Hash(String, JSON::Type), which confuses me a bit.
Any ideas how I'd be able to just get a sub-JSON from the request body, transform it to String and back to JSON?
Updated: payload is a type of JSON::Type. Casting and then calling .to_json does the trick.
require "kemal"
post "/schedule" do |env|
endpoint = env.params.json["endpoint"].as(String)
interval = env.params.json["interval"].as(Int64)
payload = env.params.json["payload"].as(JSON::Type)
env.response.content_type = "application/json"
payload.to_json
end
Kemal.run

Json.net JObject.Parse erroring on complex json

The following code:
let resp = string(argv.GetValue 0)
let json =JObject.Parse resp
gives this error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Input string '2.2.6' is not a valid number.
Path 'items[0].versionName', line 1, position 39.
where argv is this input:
{
"totalCount":1,
"items":[
{
"versionName":"2.2.6",
"phase":"PLANNING",
"distribution":"EXTERNAL",
"source":"CUSTOM",
"_meta":{
"allow":[
"GET",
"PUT",
"DELETE"
],
"href":"url",
"links":[
{
"rel":"versionReport",
"href":"url"
},
{
"rel":"project",
"href":"url"
},
{
"rel":"policy-status",
"href":"url"
}
]
}
}
]
}
How can I fix this? Is there a simple way to implement a json reader that does not error here?
I also get this error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Error parsing undefined value. Path 'items[0].name', line 1, position 28.
With this input:
{
"totalCount":1,
"items":[
{
"name":"uaa",
"projectLevelAdjustments":true,
"source":"CUSTOM",
"_meta":{
"allow":[
"GET",
"PUT",
"DELETE"
],
"href":"url",
"links":[
{
"rel":"versions",
"href":"url"
},
{
"rel":"canonicalVersion",
"href":"url"
}
]
}
}
]
}
I am trying to read in json of many different schemas that I did not make or know. The first error seems to be because it is trying to generate a float from something that should be output as a string. The second sounds like the schema is too complex and a type would be needed to properly parse it using Json.Deserialize but I'm not sure how to do that and it would take too much time as there are too many schemas to make a types for them all. Is there any way around both these things?
In C# you can use dynamic with something like this:
var json = JsonConvert.DeserializeObject(resp)
And then you could access properties with something like: json.totalCount.
In F# land, this question gives some suggestions for how you might deal with dynamic objects. If you use the package FSharp.Interop.Dynamic you can get the value of totalCount in your example with something like this:
let value:obj = json?totalCount?Value
which gives 1L on my computer.