Get length/size of json data - json

I have use the following codes to get my json data with certain nodes.
console.log(Object.keys(data.Top["person"]).length);
It is work fine in following structure of json data array:
data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}}
However when the person only have one nodes, it always show the answer 2 to me, it should be answer 1.
data:{"Top":{"person":{"A":"a","B":"b"}}}
Is it possible to solve this error?

length property is supported by type array.
data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}} in case of this person is array enclosed with [ ]
Where as for data:{"Top":{"person":{"A":"a","B":"b"}}} person is just an object. Hence length is undefined for it.
If you are creating json out of string or formatting it make sure to include [ and ] for person attribute.
JSFiddle
https://jsfiddle.net/d6pqnckh/
Also use JSON formatter to test JSON structure.
UPDATE
Since you are not sure of JSON structure. What you could do is before accessing length of person check if it is an array or object.
if(Object.prototype.toString.call(data.Top.person) === '[object Array]')
alert(data.Top.person.length);
//It is an array
else
alert("I AM OBJECT"); //It is of an object type
Updated Fiddle: https://jsfiddle.net/wys7awuz/
To make it an array regardless https://jsfiddle.net/ofkboh6k/
var p = data.Top.person;
delete data.Top.person;
data.Top.person = [];
data.Top.person.push(p);
alert(data.Top.person.length);
Include this in else part of condition. It will make it an array.

length works for type array.
change your JSON to
data:{"Top":{"person":[{"A":"a","B":"b"}]}}

Related

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]);

Get value of json string

[
{
"type": "spline",
"name": "W dor\u0119czeniu",
"color": "rgba(128,179,236,1)",
"mystring": 599,
"data": ...
}
]
I am trying to access this json as json['W doręczeniu']['mysting'], and I get no value why is that?
You're trying to access the index "W doręczeniu" but that's not an index it's a value. Also, what you seem to have is an array of JSON objects.
The [ at the start marks the array, the first element of which is your JSON object. The JSON obj begins with the {
You're also trying to use a [ ], but JSON values are accessed with the dot operator.
I'm not sure which index you're actually trying to access, but try something like this:
var x = json[0].mystring;
The value of "W doręczeniu" is not a key, so you cannot use it to get a value. Since your json string is an array you'll have to do json[0].nameto access the first (and only) element in the array, which happens to be the object. Of course, this is assuming json is the variable you store the array into.
var json = [{"type":"spline","name":"W dor\u0119czeniu","color":"rgba(128,179,236,1)","mystring":599}];
console.log(json[0].mystring); //should give you what you want.
EDIT:
To get the last element in a js array, you can simply do this:
console.log( json[json.length -1].mystring ); // same output as the previous example
'length - 1' because js arrays are indexed at 0. There's probably a million and one ways to dynamically get the array element you want, which are out of the scope of this question.

Changing an immutable object F#

I think the title of this is wrong but can't create a title that reflects, in the abstract, what I want to achieve.
I am writing a function which calls a service and retrieves data as a JSON string. The function parses the string with a JSON type provider. Under certain conditions I want to amend properties on that JSON object and then return the string of the amended object. So if the response from the call was
{"property1" : "value1","property2" : "value2", "property3": "value3" }
I want to change property3 to a new value and then return the JSON string.
If the JsonProvider was mutable this would be an exercise like:
type JsonResponse =
JsonProvider<""" {"property1" : "value1",
"property2" : "value2",
"property3": "value3" } """>
let jsonResponse = JsonResponse.Parse(response)
jsonResponse.Property3 <- "new value"
jsonResponse.ToString()
However, this does not work as the property cannot be set. I am trying to ascertain the best way to resolve this. I am quite happy to initialise a new object based on the original response but with amended parameters but I am not sure if there is an easy way to achieve this.
For reference, the JSON object is much more involved than the flat example given and contains a deep hierarchy.
Yes, you would need to create a new object, changing the bits you want and using the existing object's values for the rest. We added write APIs for both the XML and JSON type providers a while back. You will notice the types representing your JSON have constructors on them. You can see an example of this in use at the bottom of this link

Getting data from JSON Array

my JSON response is as given below
JSON response is
{"code":201,"message":[["TEST Action","NA","30-11--2011"],["TEST Action 2","NA","30-11--2011"]]}.
i want to take the data correspond to 'message'.i used JSON Array.and got response as
JSON array response is
[["TEST Action","NA","30-11--2011"],["TEST Action 2","NA","30-11--2011"]].
Now how can i access each array in that?
You should expand on what you have done, what language you are using, etc. Normally, you should be able to index into the array with the standard notation. In python for example you can do something along the lines of json_data["message"][0] to access the first array and json_data["message"][1] to access the second.
something like :
var d = JSON.parse('{"code":201,"message":[["TEST Action","NA","30-11--2011"],["TEST Action 2","NA","30-11--2011"]]}')
and then you can access each array in message part as :
d.message.forEach(function(obj) { console.log(obj); });