Accessing json generated by stringify - arrays

I have an array in which data from db is stored. I have converted this array into JSON by stringify which results in json like this:
var view_data = [{ f o o = " boo " , t e x t = "t e s t " }];
When i try to access this foo object via for loop like this :
for(var d=0; d<view_data.length; d++)
{
print view_data[d].foo;
}
It gives undefined. I think this is not actually json object is array of strings.
Please help me to access the key-value pair.

You seem to be fuzzy on the meaning of JSON. JSON is a string-based format used for exchanging data. It's not used, and is irrelevant, in the course of normal programming in JavaScript, unless you're sending data to somewhere, or receiving data from somewhere, in JSON format.
I have converted this array into JSON by stringify which results in json like this:
var view_data = [{ f o o = " boo " , t e x t = "t e s t " }];
JSON.stringify takes a JavaScript object and converts it into a string-based format. Therefore this is impossible. JSON.stringify would always return a string, not a (broken) JS object as you have shown.
In your sample data, you have shown extra spaces in the property names: "f o o" instead of "foo". If in fact that's how you have attempted to specify your JS object, it won't work at all. It's invalid syntax. It is also invalid syntax to use an equal sign; you need a colon.
If you define your JS object correctly, then the code you showed will work fine:
var view_data = [{foo: "boo" , text: "test"}];
for (var d=0; d<view_data.length; d++) {
print view_data[d].foo;
}
Accessing json generated by stringify
You don't access JSON generated by stringify. JSON is a string format meant only use in communicating with some external system.
how should then access the array as json object
There is no such thing as a JSON object. There is JSON, which is a string; and there are JavaScript objects.
For more information on JavaScript objects vs. JSON, see How to parse variables to JSON Object (Javascript).

Related

How to push object into an array? in Angular 7

I am pushing an object into an array but cannot do it?
I'm doing it like this
this.passData = this.tribeForm.value;
var id = {"tribe_id": 1}
this.passData.push(id)
This is the value in the tribeForm
I also tried
var id = {tribe_id: 1}
and
this.passData.splice(0,0, id)
and
this.passData = Array.prototype.slice(id)
and
this.passData.concat(id)
but it all ends up with
TypeError: this.passData.push/splice/concat is not a function
The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.
Example :
var object = {
name : "Jhon",
grade : 12,
gpa : 8.12
}
It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.
this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1}
You can create an empty array and push objects to it
Example :
var exampleArray = []
exampleArray.push({'tribe_id' : 1})
Now, it works because exampleArray is an Array not JS object.
Thanks for A2A
First, you need to understand the error:
TypeError: this.passData.push/splice/concat is not a function
Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.
Make sure your passData is an Array and you will able to do so.

Regex to match the last value in given data

I get data from a URL, and am working on the data to check for a few conditions. The data from the URL look like this:
1528190345":100,"1528190346":100,"1528190368":100,"1528190414":100,"1528190439":99,"1528190440":99,"1528190463":100,"1528190485":100,"1528190508":100,"1528190550":100,"1528190575":100,"1528190576":100,"1528190599":100,"1528190600":100,"1528190622":100,"1528190667":100,"1528190688":100,"1528190689":100,"1528190712":100,"1528190736":100,"1528190762":100,"1528190785":100,"1528190786":100,"1528190807":100,"1528190828":100,"1528190853":100,"1528190877":100,"1528190901":100,"1528190925":100,"1528190948":100,"1528190968":100,"1528190991":100}}]
====
I have converted that too JSON
{"metric"=>"Insta_real-unique_value", "tags"=>{"host"=>"letme.quickly.com", "tier"=>"2", "device"=>"tester1", "dc"=>"xxx"}, "aggregateTags"=>["device_name", "device_ip"], "dps"=>{"1526972408"=>100, "1526972424"=>100, "1526972440"=>100, "1526972456"=>100, "1526972472"=>100, "1526972488"=>100, "1526972504"=>100, "1526972520"=>100, "1526972536"=>100, "1526972552"=>100, "1526972568"=>100, "1526972569"=>100, "1526972584"=>100, "1526972585"=>100, "1526972601"=>100, "1526972617"=>100, "1526972633"=>100, "1526972649"=>100, "1526972665"=>100, "1526972681"=>100}}
I want to extract the value that corresponds to 100. When I do this:
url = "#{URL}"
uri = URI(url)
response = Net::HTTP.get(uri)
value = response[-6..-4]
puts value
I get the last value, but when the last value changes to 99/9/0, it prints :99 or ":9.
Is there a way to get the exact value as is?
When dealing with JSON data, it's almost always better to parse the data properly rather than using regex against the string.
In this case, we can do:
JSON.parse(response)['dps'].values.last #=> 100
If the response is a json response, you must use a json parser else if is not a json response, you can use a regex expression with a Regex Object.
In case of a json response, assuming that the object is something like is declared into the variable response of the next code, you can parse it into a JObject. (using Newtonsoft.Json available from nuget repository).
See the next example :
string response = "[{\"response\":{\"1528190345\":100,\"1528190346\":100,\"1528190368\":100,\"1528190414\":100,\"1528190439\":99,\"1528190440\":99,\"1528190463\":100,\"1528190485\":100,\"1528190508\":100,\"1528190550\":100,\"1528190575\":100,\"1528190576\":100,\"1528190599\":100,\"1528190600\":100,\"1528190622\":100,\"1528190667\":100,\"1528190688\":100,\"1528190689\":100,\"1528190712\":100,\"1528190736\":100,\"1528190762\":100,\"1528190785\":100,\"1528190786\":100,\"1528190807\":100,\"1528190828\":100,\"1528190853\":100,\"1528190877\":100,\"1528190901\":100,\"1528190925\":100,\"1528190948\":100,\"1528190968\":100,\"1528190991\":100}}]";
List<Dictionary<string, Dictionary<string, int>>> values = JsonConvert.DeserializeObject<List<Dictionary<string, Dictionary<string, int>>>>(response);
Dictionary<string, Dictionary<string, int>> firstLevel = values[0]; // Access to the first object of the list closed with ']'
Dictionary<string, int> secondLevel = firstLevel["response"]; // Access to the first object response and get's it's object context of first '}' starting from the end of response
/** This is an option, if you ever knows the name of the element (1528190991) */
int thirdLevel = secondLevel["1528190991"]; // Access to the last element of the object by it's name, context of second '}' starting from the end of response.
Console.WriteLine(thirdLevel);
/** This is another option if you doesn't know the name of the element and wants ever the last element. */
List<int> listOfValues = secondLevel.Values.ToList();
Console.WriteLine(listOfValues[listOfValues.Count-1]);
Note that i've chenged a little bit your response adding [{\"response\":{\" at the start to become a json response.
If is not a json response you can use this pattern with regular expression :
:(.{2,6})}}\]$
Hope will help!

How to read nested JSON in Codename One

I have been following the instructions here:
https://www.codenameone.com/javadoc/com/codename1/io/JSONParser.html to retrieve a value from a json file.
I have managed to read the top level value of my json content - however I cannot see how to read the value of a nested tag e.g. using this file ...
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
Please can someone show me how to get to the value of "para" above?
Thanks
After parsing your json data based on this, you can use Result to read deep into the json content:
import com.codename1.processing.Result;
...
Map<String, Object> data = json.parseJSON(r);
Result result = Result.fromContent(data);
String id = result.getAsString("glossary/GlossDiv/GlossList/GlossEntry/ID");
String para = result.getAsString("glossary/GlossDiv/GlossList/GlossEntry/GlossDef/para");

Parse Array of JSON Objects in Crystal lang

Suppose I've got a simple JSON mapped object in Crystal lang, e.g.:
class Item
JSON.mapping(
id: UInt32,
name: String,
)
end
I can parse individual objects from JSON strings easily like so:
foo = Item.from_json(%({"id":1,"name":"Foo"}))
puts "OK: foo=#{foo}"
# => OK: foo=Item(#id=1, #name="Foo")
But how would I parse an array of Items from a JSON string? I've tried a few approaches but am not sure how to proceed, e.g.:
items_str = %([{"id":1,"name":"Foo"},{"id":2,"name":"Bar"}])
items : Array(Item) = JSON.parse(items_str)
# => Error in foo.cr:15: type must be Array(Item), not JSON::Any
Of course, I'd also like to be able to do this with a JSON pull parser, so presumably there's some mapping trick or type hint I'm missing. Ideas?
Found it in this spec. So, you can use Array(Item).from_json:
items = Array(Item).from_json %([{"id":1,"name":"Foo"},{"id":2,"name":"Bar"}])
items.first.id #=> 1
items.first.name #=> "Foo"
items.last.id #=> 2
items.last.name #=> "Bar"

google visualization data.addRow - get data out of html data attribute

I have data inside a data attribute, like so:
<div class="dashboard-module" data-rows="new Date(2013,10,04),12,"OR"##new Date(2013,10,17),2,"OR"##new Date(2013,10,09),2,"CA""></div>
Im trying to split this string up and use it in the data.addRow function:
rows = el.data('rows');
rowsarray = rows.split('##');
// Error: Row given with size different than 3 (the number of columns in the table).
$.each(rowsarray, function(index, value) {
data.addRow( [value] );
});
// the following works
data.addRow([new Date(2013,10,04),12,"OR"]);
data.addRow([new Date(2013,10,09),2,"CA"]);
data.addRow([new Date(2013,12,12),14,"AL"]);
I guess the commas inside the new date are being counted as different parts of the array?
I'm assuming that the double-quotes inside your data-rows attribute are escaped (otherwise the HTML is malforned).
When you call rowsarray = rows.split('##');, you are getting an array of strings, like this:
[
'new Date(2013,10,04),12,"OR"',
'new Date(2013,10,17),2,"OR"',
'new Date(2013,10,09),2,"CA"'
]
not an array of arrays. If you want to store your data in an HTML attribute, your best bet is to use a JSON-compatible format. The problem then becomes storing dates, since Date objects are not JSON-compatible, but that is easy to work around. Store your data like this instead:
[["Date(2013,10,04)",12,"OR"],["Date(2013,10,17)",2,"OR"],["Date(2013,10,09)",2,"CA"]]
I did two things with the data-rows attribute: first, I changed the dates from a format like new Date(2013,10,17) to a string like "Date(2013,10,17)". Second, I converted the string to a JSON string representation of an array of arrays (which uses the standard javascript array brackets [ and ]). Note that JSON requires the use of double-quotes for all internal strings, so you must either escape all internal strings to use with the data-rows attribute, or use single-quotes around the data-rows attribute string (eg: data-rows='<string>').
You can then parse that string for entry into your DataTable:
rows = JSON.parse(el.data('rows'));
// convert date strings to Date objects
for (var i = 0; i < rows.length; i++) {
var dateStr = rows[i][0];
var dateArr = dateStr.substring(5, dateStr.length - 1).split(',');
rows[i][0] = new Date(dateArr[0], dateArr[1], dateArr[2]);
}
data.addRows(rows);

Resources