How to access json inputs - json

I am working in yii framework.I am having json input as-
$json='{"userId":1,"questionPaperId":1;"optionId":2}';
So whilw creating functions in yii,i am decoding it and accessing these inputs as-
$obj=CJSON::decode($json);
$option=$obj->optionId;
$userId=$obj->userId;
$paperId=$obj->questionPaperId;
But its giving error as "Trying to get property of non-object ". So how to access this in yii?

You json string is syntax wrong.
$json='{"userId":1,"questionPaperId":1;"optionId":2}'; // note the ; in it
should be
$json='{"userId":1,"questionPaperId":1,"optionId":2}';

As CJSON::encode give you a json formatted string from an array, CJSON::decode return an array not an object.
So access it like that: $option=$obj["optionId"];

Related

Dynamic deserialize JSON from method

How to dynamic deserialize JSON from method in controller? I use that code:
dynamic dynJson = JsonConvert.DeserializeObject(GetReservedDaysJson().ToString());
And have that error:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: M. Path '', line 0, position 0.'
My JSON from GetReservedDaysJson() function look like that:
["2022-03-29","2022-03-30"]
Unless someone has a better solution. It needs to compare each date with JSON. With the date provided in the model.
you can try this
string json = GetReservedDaysJson();
List<DateTime> dates = JsonConvert.DeserializeObject<List<DateTime>>(json);

Why does it say in runtime that my json field is empty?

I have a json field: recurringindicator and it's value has to be 'true'.
So I am building my json like this:
Writer.WriteStartObject;
Writer.WritePropertyName('access');
Writer.WriteStartObject;
Writer.WritePropertyName('balances');
Writer.WriteStartArray;
Writer.WriteEndArray;
Writer.WritePropertyName('transactions');
Writer.WriteStartArray;
Writer.WriteEndArray;
Writer.WriteEndObject;
Writer.WritePropertyName('recurringIndicator');
Writer.WriteValue(true);
Writer.WritePropertyName('validuntil');
Writer.WriteValue('2021-12-31');
Writer.WritePropertyName('frequencyPerDay');
Writer.WriteValue('4');
Writer.WriteEndObject;
Showmessage(StringBuilder.ToString);
which builds the json string:
{"access":{"balances":[],"transactions":[]},
"recurringIndicator":true,
"validUntil":"2021-12-31",
"frequencyPerDay":"4"}
but in runtime I get that the "recurringIndicator" field is empty.
Can somebody please help me with this?
Restrequest2.AddBody(StringBuilder);
Restrequest2.Execute;
In this call
Restrequest2.AddBody(StringBuilder);
you are serializing the StringBuilder instance instead of the string content.
This should work:
Restrequest2.AddBody(StringBuilder.ToString, TRESTContentType.ctAPPLICATION_JSON);

Single value from json array using nodejs

so i have this data which is outputted from stringify(doc)
{
"id": "8467fdae-c38c-4b6e-9492-807d7c9eb97e",
"message": "send to nodejs"
}
but im not sure how can i go ahead in getting a single value from it, e.g message. Any help would be appreciated as ive tried different methods and they seem to not be working
After you use stringify method the value you have is string.
So You can not get single property from it, except you convert it become object again and get property it. Like this:
object = {
"id": "8467fdae-c38c-4b6e-9492-807d7c9eb97e",
"message": "send to nodejs"
};
// JSON string is value which you get after use Stringify method
jsonString = JSON.stringify(object);
// Convert jsonString to object again and get message property
message = JSON.parse(jsonString).message
stringify() will convert json to string.
Before running stringify(), doc is already json and you can get message by doc.message.
after running stringify(), the result will be string, if you want to get json back, you can use JSON.parse()

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

Display JSON Object from console

I have a JSON object returned in my console, and I want to display those data named "offers".
the JSON object is returned like that :
I tried to display my JSON Object data with :
console.log(JSON.stringify(data));
The thing is, it says that "data is not defined"
Does anyone know what happens ? :)
You should add full path to element of json, for example if your json looks like:
var json = {"par":22, "par2":555, "elems":[{"attr1":53, "attr2":99}] };
and if you want to get attr1 value, you should do something like this:
console.log(json.elems[0].attr1); // 53
so in your case that could be something like:
variableName.result.data.offers //variableName is variable that your "consoling"
Method JSON.stringify doesn't get yout specified value from JSON structure, it's converts JSON object to string.
console.dir provides a good representation of object than console.log().U can try with both
console.log(result.data.offers[0]);
console.dir(result.data.offers[0]);