Parsing json array to array javascript - javascript

I have an array with json data:
var jsonString=[
{
"url": "http://www.anurl.com",
"tags": {
"Event": 6,
"Event1": 2
}
}
]
Now i want to build the next structure:
var data= [ {"text":"Event", "weight" : "6", "link" :"www.anurl.com"} //etc ];
Now i looked into the var array = $.parseJSON(JSON.stringify(jsonString));
and on the result i try to build my data array with .push();
But how can i insert the Event: 6 part? i cannot do array.tags[0] as array.tags will give me both of them.
So how can i solve this problem?

You are using object literals in javascript, the example you provided:
var jsonString=[{
"url": "http://www.anurl.com",
"tags": {
"Event": 6,
"Event1": 2
}
}];
jsonString is an array, and the element tags is an object NOT an array so you can access it like this:
var event = jsonString[0].tags.Event;

You can read the attributes of the tags object like the example below :
function loadArray(urls){
xhrDoc= new XMLHttpRequest();
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined');
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
printUrls(data);
}
}
};
xhrDoc.open('GET', urls , true);
xhrDoc.send();
}
function printUrls(response) {
var arr = JSON.parse(response);
var i;
var out = "";
for(i = 0; i < arr.length; i++) {
console.log(arr[i].url);
console.log(arr[i].tags['Event']); // Read Event
console.log(arr[i].tags['Event1']); //// Read Event1
out = "URL : "+ arr[i].url + " Event : "+ arr[i].tags['Event']+ " Event1 : " + arr[i].tags['Event1'] + "\n";
}
document.getElementById("id01").innerHTML = out;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="parseJsonFile.js"></script>
</head>
<body onload="loadArray('parseJson.json')">
<div id="id01"></div>
</body>
</html>

i solved it with
this code
var array =$.parseJSON(JSON.stringify(jsonString));
for (var i = 0; i < array.length; i++) {
var keys =array[i].tags;
var tags = Object.keys(keys);
for(var j = 0 ; j<tags.length; j++){
var obj = {text : tags[j], weight : keys[tags[j]] , link : array[i].url};
Jarray.push(obj);
}
}
The data is provided by an API, so the tag Event : 6 might be the next time Tomorrlowland : 3 the name of event and the weight are given by the API. That's why i can't use jsonString[0].tags.Event because the name event will be different every time.
Thanks all for helping me !

Related

Parsing data from api in javascript

I am trying to parse data from a wordpress json api to my ionic app, Data from api is coming as:
{
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"],
---------------
-------------
--------------
-------------
"event":["3"] this shows total number of events
}
Using javascript, how would I format the above data and save it to some variable so that I can render it easily?
events:[
{
"date_from":"20191015",
"date_to":"20190926",
"event":"Winter Vacation",
"description":"Winter vacation"
},
{
"date_from":"20191015",
"date_to":"20190926",
"event":"Winter Vacation",
"description":"Winter vacation"
},
{
"date_from":"--some-data--",
"date_to":"--some-data--",
"event":"--some-data--",
"description":"--some-data--"
},
---------------
-------------
--------------
-------------
]
I tried so many methods but none are working.
I think your just should take "yourObjekt.event[0]" for a counter like:
var newObjekt = [];
for (var i=0; i<yourObjekt.event[0]; i++) {
newObjekt[i] = {
date_from: yourObjekt["event_"+i+"_date_from"][0],
date_to: yourObjekt["event_"+i+"_date_to"][0],
event: yourObjekt["event_"+i+"_event"][0],
description: yourObjekt["event_"+i+"_description"][0]
}
}
You just need to iterate over your json object. Within each iteration create a new map and push this newly created map into an array. Following is working snippet.
let data = {
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"],
"event":["3"]
}
let array = [];// Initialize an array
let index = data.event[0];// Number of events
for(let i=0;i<index;i++){
let map = {};//Initialize a new map in each iteration.
map.date_from = data["event_"+i+"_date_from"][0];
map.date_to = data["event_"+i+"_date_to"][0];
map.event = data["event_"+i+"_event"][0];
map.description = data["event_"+i+"_description"][0]
array.push(map);// finally push map into array
}
console.log(array);
Try this code, it will include all event attributes in a dynamic way
var output = [];
for(var key in datas){
// parse key
var keyParts = key.split('_');
var value = datas[key];
// ignore "event" total
if(keyParts.length > 1){
var key = keyParts.slice(2).join('_'); // generate correct key from parts
var index = keyParts[1]; // indexes : 0, 1, 2, etc.
// initialize in first call
if(output.hasOwnProperty(index) === false){
output[index] = {}
}
// append to output
output[index][key] = value
}
}
Withing 20 minutes with Googling (+ few minutes for proper adjustment of counters) ... (wrote JS few times in whole life)
I was not sure how to load it into String and did not wanted to escape whole string, so I am loading it from a text file
Input data:
{
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"]
}
Page and script:
<!DOCTYPE HTML>
<html>
<body>
<input type="file" id="upload">
<script>
document.getElementById('upload').addEventListener('change', readFileAsString)
function readFileAsString() {
var files = this.files;
if (files.length === 0) {
console.log('No file is selected');
return;
}
var reader = new FileReader();
reader.onload = function(event) {
//console.log('File content:', event.target.result);
var inputStr = event.target.result;
//console.log(inputStr);
var obj = JSON.parse(inputStr);
//console.log(obj);
var hasNext=true;
var counter = 0;
while(hasNext){
var properties =["date_from","date_to","event","description"];
var propertyPrefix = "event_"
var prop = propertyPrefix + counter + "_" + properties[0];
if(obj.hasOwnProperty(prop)){
console.log("element #" + counter + ": ")
for(var i = 0; i< properties.length;i++){
var propToPrint = propertyPrefix + counter + "_" + properties[i];
//console.log("loading: " + propToPrint)
console.log(" " + obj[propToPrint]);
}
counter++;
}else{
hasNext = false;
}
}
};
reader.readAsText(files[0]);
}
</script>
</body>
</html>
Result:
element #0:
20191015
20190926
Winter Vacation
Winter vacation
element #1:
20190917
20190930
Dashain Vacation
--some-data--
element #2:
--some-data--
--some-data--
--some-data--
--some-data--
So, eg. this way its possible :)

Why is this JSON file reading strangly

I have a JSON document here. I have validated it with JSlint.
The JSON is of this format:
[{
"date": "2017-02-10",
" action": "Do a thing",
"state": "closed",
"url": "https:someurl.com"
},
....
I have some HTML here, which exists only to read and output the JSON.
The HTML looks like this:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
<script>
deadlines = []
start();
function start() {
var req = new XMLHttpRequest();
req.open("GET", "http://joereddington.com/deadlines.json");
req.overrideMimeType("application/json");
req.send(null);
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var obj = JSON.parse(req.responseText);
deadlines = obj
for (deadline in deadlines) {
var output = '';
for (var property in deadline) {
console.log(property)
output += property + ': ' + deadline[property] + '; ';
}
console.log(output);
console.log(deadline.date)
console.log(deadline.action)
}
}
};
}
</script>
</body>
However, when I try and list the properties of each object, I get very strange results:
rather than the names and values I'm looking for. Can someone tell me what I'm doing wrong?
$.each(JSON.parse(deadlines), function (index, deadline) {
var output = '';
for (var property in deadline) {
console.log(property)
output += property + ': ' + deadline[property] + '; ';
}
console.log(output);
console.log(deadline.date);
console.log(deadline.action);
});
Your JSON string contains extra space. It should be "action" not " action".
for...in loops over the keys (since it's an array: "0", "1" ...). Use for...of or forEach or a basic for loop.
I recommend forEach like this:
deadlines.forEach(function(deadline) {
// ...
});

How to fetch image through json using jquery or JS in HTML

Can any body help, m totally new in Json I want to fetch the image but m bit confuse in the array and object thing. Or is it possible to fetch image without img tag. Thank you in advance
This is my JSON link
this what I have tried:
function myFunction(worldpopulation) {
var out = "";
var i;
for(i = 0; i<worldpopulation.length; i++)
out += '' + worldpopulation[i].rank;
document.getElementById("id01").innerHTML = out;
}
just help me to fetch "rank" only
{ "worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
},
{
"rank":3,"country":"United States",
"population":"315,761,000",
"flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
},
]
}
The first thing you will get the content of your json content from this page using XMLHttpRequest
var request = new XMLHttpRequest();
var url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";
request.onreadystatechange = function() {
if(request.readyState == && request.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
the implementation of myFunction
function myFunction(myArr)
{
for(var i=0; i< myArr.length; ++i) {
var img ; // get your element you want to place img inside
img.src = myArr[0].flag;
}
}
you can use .filter() to get image array.
var imageArr = [];
imageArr = worldpopulation.filter(function(val,indx){
return val.flag;
});
you can use jquery in following way
$.getJSON( "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt",function( data ) {
$.each( data.worldpopulation, function( key, country) {
console.log('Image Url',country.flag)
});
});

convert json to array using jquery

The result of my php is
$result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}]';
and done json parse to it
var data = new Array();
data = JSON.parse('<?php echo $result ; ?>');
How will I get the output as
MFG_NAME[0] = ABC;
MFG_NAME[1] = XYZ;
DATE[0] = [01-MAR-14,01-APR-14,01-MAY-14];
DATE[1] = [01-MAR-14,01-APR-14,01-MAY-14];
MKT[0] = [0.59,0.25,0.10];
MKT[1] = [0.87,0.67,0.03];
Loop through data, building your arrays. First check to see if you already have a matching MFG_NAME by using indexOf(). If you have a match, use that index for the other arrays. Otherwise create new entries for each variable.
var data = [
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-MAR-14|0.59" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-MAR-14|0.87" },
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-APR-14|0.25" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-APR-14|0.67" },
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-MAY-14|0.10" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-MAY-14|0.03" }
];
var MFG_NAME = [];
var DATE = [];
var MKT = [];
data.forEach(function(item) {
var parts = item.CONCATED_MKT_SHARE.split("|");
var i = MFG_NAME.indexOf(item.MFG_NAME);
if (i == -1) {
MFG_NAME.push(item.MFG_NAME);
DATE.push([parts.shift()]);
MKT.push([+parts.shift()]);
}
else {
DATE[i].push(parts.shift());
MKT[i].push(+parts.shift());
}
});
var success = MFG_NAME[0] == "ABC" &&
MFG_NAME[1] == "XYZ" &&
DATE[0].join(",") == "01-MAR-14,01-APR-14,01-MAY-14" &&
DATE[1].join(",") == "01-MAR-14,01-APR-14,01-MAY-14" &&
MKT[0].join(",") == "0.59,0.25,0.1" &&
MKT[1].join(",") == "0.87,0.67,0.03";
document.write(success);
This requires your data to be sorted by date. Your sample data is already sorted by date then name. This will still work if it's sorted by name then date, or if it's sorted by only date, not considering name at all. But, If it's not sorted by date at all, you'll need to do an extra step to sort first (which would be inefficient), or adjust the code to sort as you process the data.
$result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}];';
var_dump(json_decode($result, true));
Maybe it's your solution?!
I guess this is what you want:
var $result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}]';
var data = new Array();
data = JSON.parse($result);
var MFG_NAME = new Array();
var DATE = new Array();
var MKT = new Array();
var i = 0;
$.each( data, function( key, value ) {
MFG_NAME[i] = value.MFG_NAME;
var MKT_SHARE = value['CONCATED_MKT_SHARE'].split('|');
DATE[i] = MKT_SHARE[0];
MKT[i] = MKT_SHARE[1];
i++;
});
console.log(MFG_NAME[0]);
console.log(MFG_NAME[1]);
console.log(MFG_NAME);
console.log(DATE);
console.log(MKT);
Demo: http://jsfiddle.net/1n51kwze/
var MFG_NAME = [];
var DATE = [];
var MKT = [];
//For each data entry
for(i = 0; i < data.length; i++){
concatString = data[i]["CONCATED_MKT_SHARE"].split("|");
//If name not exists create date and mkt object for name instance
if(MFG_NAME.indexOf(data[i]["MFG_NAME"]) == -1){
MFG_NAME[i] = data[i]["MFG_NAME"];
DATE[i] = [];
MKT[i] = [];
DATE[i].push(concatString[0]);
MKT[i].push(concatString[1]);
}else{
//Else just add to existing
DATE[MFG_NAME.indexOf(data[i]["MFG_NAME"])].push(concatString[0]);
MKT[MFG_NAME.indexOf(data[i]["MFG_NAME"])].push(concatString[1]);
}
}
console.log(MFG_NAME[0]);
console.log(MFG_NAME[1]);
console.log(DATE[0]);
console.log(DATE[1]);
console.log(MKT[0]);
console.log(MKT[1]);
Result looks like this:
ABC
XYZ
["01-MAR-14", "01-APR-14", "01-MAY-14"]
["01-MAR-14", "01-APR-14", "01-MAY-14"]
["0.59", "0.25", "0.10"]
["0.87", "0.67", "0.03"]
Hope this helps :)
You could do that like this:
var data = [{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}];
var MFG_NAME = [],
DATE = [],
MKT = [];
for(var i = 0; i < data.length; i++){
MFG_NAME.push(data[i].MFG_NAME);
var split = data[i].CONCATED_MKT_SHARE.split("|");
DATE.push(split[0]);
MKT.push(split[1]);
}
alert("MFG_NAME:\n" + JSON.stringify(MFG_NAME) + "\n\n" +
"DATE:\n" + JSON.stringify(DATE) + "\n\n" +
"MKT:\n" + JSON.stringify(MKT));
As you can see, this will result in 3 new arrays containing your data, separated by key.
Oh, and you don't need to declare data before adding properties to it. This'll work just fine:
var data = JSON.parse('<?php echo $result ; ?>');

How do I iterate over a JSON structure? [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have the following JSON structure:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
How do I iterate over it using JavaScript?
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
note: the for-in method is cool for simple objects. Not very smart to use with DOM object.
Taken from jQuery docs:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Use for...of:
var mycars = [{name:'Susita'}, {name:'BMW'}];
for (var car of mycars)
{
document.write(car.name + "<br />");
}
Result:
Susita
BMW
Please let me know if it is not easy:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
If this is your dataArray:
var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];
then:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var CLASS = this.class;
});
Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
RESULT: John Doe 25
mootools example:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
You can use a mini library like objx - http://objx.googlecode.com/
You can write code like this:
var data = [ {"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}];
// alert all IDs
objx(data).each(function(item) { alert(item.id) });
// get all IDs into a new array
var ids = objx(data).collect("id").obj();
// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()
There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary
With nested objects, it can be retrieve as by recursive function:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
where as events is json object.
Marquis Wang's may well be the best answer when using jQuery.
Here is something quite similar in pure JavaScript, using JavaScript's forEach method. forEach takes a function as an argument. That function will then be called for each item in the array, with said item as the argument.
Short and easy:
var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"} ];
results.forEach(function(item) {
console.log(item);
});
this is a pure commented JavaScript example.
<script language="JavaScript" type="text/javascript">
function iterate_json(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
hr.open("GET", "json-note.php", true);//this is your php file containing json
hr.setRequestHeader("Content-type", "application/json", true);
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("myDiv");//myDiv is the div id
for (var obj in data){
results.innerHTML += data[obj].id+ "is"+data[obj].class + "<br/>";
}
}
}
hr.send(null);
}
</script>
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here
var jsonString = `{
"schema": {
"title": "User Feedback",
"description": "so",
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
},
"options": {
"form": {
"attributes": {},
"buttons": {
"submit": {
"title": "It",
"click": "function(){alert('hello');}"
}
}
}
}
}`;
var jsonData = JSON.parse(jsonString);
function Iterate(data)
{
jQuery.each(data, function (index, value) {
if (typeof value == 'object') {
alert("Object " + index);
Iterate(value);
}
else {
alert(index + " : " + value);
}
});
}
Iterate(jsonData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another solution to navigate through the JSON document is JSONiq (implemented in the Zorba engine), where you can write something like this:
let $doc := [
{"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class (: gets the value associated with "class" :)
You can run it on http://public.rumbledb.org:9090/public.html

Categories