Convert JSON to java script [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Can anybody provide the java script for the below JSON. I tried in many way, but could not add the field "set"
{
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
}

So your javaScript variable would be an objecthaving property/key name student of array type. Now student has two elements set a string and an object, other element is also an array, has an element of object type. This element has two properties/keys name and id.
var required = {};
required.student = [];
required.student.push("set");
var innerArray = [];
var innerObj = {};
innerObj.name = "abcd";
innerObj.id = "1234";
innerArray.push(innerObj);
required.student.push(innerArray);
document.write('<pre> ' + JSON.stringify(required,0, 3) + '</pre>');

JSON.parse(jsonString);
Is a pure JavaScript approach so long as you can require a reasonably modern browser.
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

I'm not sure what you are trying to do, but...
If you just want to have the JSON object you described available in your JavaScript code, you can just put it into a variable.
var json = {
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
};
// Testing the object:
// Print the JSON object we made, as a string
console.log(JSON.stringify(json));
// Print the first item inside the 'student' array
console.log(json.student[0]);
If you instead have your JSON as a string, you can parse it to JSON object with:
var json = JSON.parse(jsonString);

Related

Comparing keyword value field in array - Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have keyword (for example -2330) that needs to be compared with the 'values' in this string below.
"[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
Expected output needs to be true or false depending if the string has the keyword or not.
How do I check it?
I will do something like this to loop
var a = "[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
var new_a = JSON.parse(a);
var value_compare = '1574';
new_a[0]['value'].forEach(element => {
if (element[0].value == value_compare) {
//DO SOMETHING
alert('found: '+ JSON.stringify(element));
}
});
You first need to parse the JSON into an suitable JS structure. Because of the nested nature of the data you need to 1) map over the first object in your array, 2) return the value of the value property of the first object of each and finally 3) check to see if the keyword is included in the the returned array, and return true or false.
const json = '[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]';
const data = JSON.parse(json);
function doesItExist(data, keyword) {
const values = data[0].value.map(arr => arr[0].value);
return values.includes(keyword);
}
console.log(doesItExist(data, '2331'));
console.log(doesItExist(data, 'Bob'));
console.log(doesItExist(data, '1574'));

How to convert a string look like an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I make a get request to URL "http://cafef3.mediacdn.vn/v2/kby/ccf4d584-4b06-4370-acff-c0241b4ad0d6/kby.js". It is a javascript file and I get a string "var oc=[object_1, object_2]".
How can I create a new array based on the string above? e.g. let newArray = [object_1, object_2]
Thank!
Assuming it's for browser.. you could create a new script tag (so that the content of the javascript file will be parsed) and then assign the new variable from there.
Here is some code for reference:
const newScriptTag = document.createElement('script')
newScriptTag.textContent = content; // content is the value of the js file (var oc... )
document.body.append(newScriptTag)
let newArray = oc;
// then remove the script tag
document.body.removeChild(scriptTag)
Well, you could get rid go the prefix and suffix of your string using something like:
let result = 'var oc=["object_1", "object_2"];';
result = result.replace('var oc=','');//to remove the variable definition from the start
result = result.slice(0,-1);//to remove ';' at the end. You can use this, because strings are arrays of characters
And then use:
result = JSON.parse(result);//this should give you a nice array with your objects in it
You can find references for the methods I mentioned from a couple of different sources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://www.w3schools.com/jsref/jsref_replace.asp
https://www.w3schools.com/jsref/jsref_slice_array.asp
EDIT:
That last part with JSON.parse() would work if the return for your request was a valid JSON. but it's not, that's JS code, representing the definition of an object. To parse that, you could use eval(). But you should exercise caution and only use that in strings that return from trustworthy sources, since that could inadvertently execute malicious code inside your code.
That said, the last line of code to solve your problem would be something like:
result = eval(result)
console.log(result);
Thankfully, there's a better way to do it using Function() like so:
result = Function('"use strict";return (' + result + ')')
console.log(result());
You can read the reference from these two last ways of parsing code as string in here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!
Turn each object into an array using Object.entries and merge the arrays.
const obj1 = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 };
const obj2 = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 };
const myArray = Object.entries(obj1).concat(Object.entries(obj2));;
console.log(myArray);

How to access elements of json array using javascript/jquery? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a json array like this
AlreadySaved:[
{
"SNO":1,
"SNUMBER":"827",
"STARTDATE":"11/12/2016",
"STARTTIME":"03:06:50 PM",
"ITEMNAME":"KBand",
"ITEMCODE":"KB2541",
"ITEMSKUNAME":"Band",
"ITEMSKUCODE":"BT102",
"SALESRATE":100.0,
"PURCHASERATE":5.0,
"DOE":"~",
"STOCKQTY":2.0,
"PHYSICALQTY":1.0
}
]
I need to fetch value of PHYSICALQTY and display it in alert.I am new to jquery/javascript so any help would be appreciated.
You can access json like normal objects in js via dot notation.
var json = {"STOCKQTY":2.0,"PHYSICALQTY":1.0};
console.log(json.PHYSICALQTY);
If you Have saved this json under another object You need to go deeper, eg.
var response = {AlreadySaved: [{"STOCKQTY":2.0,"PHYSICALQTY":1.0}] };
console.log(response.AlreadySaved[0].PHYSICALQTY);
Please remember also that in some cases You may have json (eg from response) as string not object.
console.log(typeof someJson); //string
In that cases You need to parse this string into json
var json = JSON.parse(someJsonAsString);
Happy hacking!
You can use json[0].PHYSICALQTY
var json = [{
"SNO": 1,
"SNUMBER": "827",
"STARTDATE": "11/12/2016",
"STARTTIME": "03:06:50 PM",
"ITEMNAME": "KBand",
"ITEMCODE": "KB2541",
"ITEMSKUNAME": "Band",
"ITEMSKUCODE": "BT102",
"SALESRATE": 100.0,
"PURCHASERATE": 5.0,
"DOE": "~",
"STOCKQTY": 2.0,
"PHYSICALQTY": 1.0
}];
document.getElementById('id1').innerHTML=json[0].PHYSICALQTY;
<div>
PHYSICALQTY:<label id="id1"></label>
</div>
You can parse this and then get the value. Ouf course if you receive this like a string.
var a = '[{"SNO":1,"SNUMBER":"827","STARTDATE":"11/12/2016","STARTTIME":"03:06:50 PM","ITEMNAME":"KBand","ITEMCODE":"KB2541","ITEMSKUNAME":"Band","ITEMSKUCODE":"BT102","SALESRATE":100.0,"PURCHASERATE":5.0,"DOE":"~","STOCKQTY":2.0,"PHYSICALQTY":1.0}]'
var output = JSON.parse(a)
console.log(output[0].PHYSICALQTY)
Your JSON object is not valid, you can check that at http://jsonlint.com/
Once you set it to something like
var AlreadySaved =[{"SNO":1,"SNUMBER":"827","STARTDATE":"11/12/2016","STARTTIME":"03:06:50 PM","ITEMNAME":"KBand","ITEMCODE":"KB2541","ITEMSKUNAME":"Band","ITEMSKUCODE":"BT102","SALESRATE":100.0,"PURCHASERATE":5.0,"DOE":"~","STOCKQTY":2.0,"PHYSICALQTY":1.0}] ;
you can access it via AlreadySaved[0]["PHYSICALQTY"]
It is not json object.
Json:
{AlreadySaved:[{"SNO":1,"SNUMBER":"827","STARTDATE":"11/12/2016","STARTTIME":"03:06:50 PM","ITEMNAME":"KBand","ITEMCODE":"KB2541","ITEMSKUNAME":"Band","ITEMSKUCODE":"BT102","SALESRATE":100.0,"PURCHASERATE":5.0,"DOE":"~","STOCKQTY":2.0,"PHYSICALQTY":1.0}]}
In this case you may get your property:
alert(AlreadySaved[0].PHYSICALQTY);
firstly you have to serialize your object like this;
var json_data = JSON.parse(AlreadySaved);
and if you know specific data in json_data, you can call with index number like this;
var result= json_data[0]["PHYSICALQTY"];
Or you can find whatever you want, you can find with foreach;
for(var item in json_data) {
alert(item["PHYSICALQTY"].value);
}
Please try this:
//In case you are getting this from ajax request put "returnObject.Json_Variable" instead of "Json_Variable"
var obj = (JSON.parse("Json_Variable"));
var resultPHYSICALQTY=obj.PHYSICALQTY);

Issue with Undefined JSON Variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a basic Node.js script that creates a JSON array from a few variables and other arrays.However, whenever I call on myJSON.title in my code it does not work at all. It gives undefined. Could anyone please help me?
for (var i = 0; i < route.length; i++) {
var item = {
"title": title[i],
"date": date[i],
"summary": summary[i],
"route": route[i],
"pebbleid": "geoquery-" + timegreeting + route[i]
};
myarray.push(item);
for (var i = 0; i < route.length; i++) {
var item = {
"title": title[i],
"date": date[i],
"summary": summary[i],
"route": route[i],
"pebbleid": "geoquery-" + timegreeting + route[i]
};
myarray.push(item);
}
myJSON = JSON.stringify({delays: myarray});
console.log(myJSON);
}
The reason myJSON.title is undefined is that JSON.stringify returns a string, and strings don't have a title property.
The object represented by the JSON string myJSON has a single property, delays, (because that's what you put in JSON.stringify). The value of that property is an array. Each element of that array is an object that has a title property (and date, summary, etc.). So to get any one title, you first have to retrieve the delays array and then retrieve one of its elements by index, and then retrieve that element's title property.
So for e.g. the 0th element in delays, you would do this:
obj.delays[0].title
I used "obj" because this will not work with myJSON, because like I said, in the code you've shown myJSON is a JSON string, not a JavaScript object, and so doesn't have a delays property.

How return this data in json for each? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i have json values like this, i try to use for each to get the result one bye one, but it was not returning to me
"[{"id":6,"userid":13,"title":"business3","bussinessTypeid":1,"photurl":"","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":7,"userid":13,"title":"business6 arabic","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":10,"userid":13,"title":"E-commerce","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":11,"userid":8,"title":"Auto phone parts","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":19,"userid":8,"title":"التجارة الإلكترونية","bussinessTypeid":1,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":20,"userid":8,"title":"E-commerce -online shopping","bussinessTypeid":8,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":21,"userid":13,"title":"My new Business","bussinessTypeid":6,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]}]"
can anyone guide me to achive this
I think it's being treated as a string try to remove the ( " ) on the start and end of it something like:
var json = [{"id":6,"userid":13,"title":"business3","bussinessTypeid":1,"photurl":"","cntry":[{"id":"9","name":"Bahrain"}]},{"id":7,"userid":13,"title":"business6 arabic","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":10,"userid":13,"title":"E-commerce","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":11,"userid":8,"title":"Auto phone parts","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":19,"userid":8,"title":"التجارة الإلكترونية","bussinessTypeid":1,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},{"id":20,"userid":8,"title":"E-commerce -online shopping","bussinessTypeid":8,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},{"id":21,"userid":13,"title":"My new Business","bussinessTypeid":6,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]}];
Then do the iteration:
for(id in json){
alert(json[id]['id']);
}
and don't include any next line spaces are ok as long as they are separated by a comma (,)
Use parseJson()
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
$.each(data, function(key, value){
console.log(value.id, value.title);
$.each(value.cntry, function(key2, value2){
console.log(value2.id, value2.name);
})
});
Try this with jquery
var data = jQuery.parseJSON(yourJsonInString); //or this parser below
var data = JSON.parse(yourJsonInString);

Categories