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);
Related
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);
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);
I have this javascript file which looks like below:
var abc= {
"a" : {
"label": "Monthly",
"URL": "xyz.com",
"ArchTag": "M",
"archData": {
"Feb 2016":"20160229",
"Jan 2016":"20160129",
"Dec 2015":"20151231"
}}};
so I want a way to edit this and say add a new month detail. I guess its a json inside javascript. So how can one edit it in a standard way.
If you can rely on the data looking exactly like this every time then you can just hack off the bit that stops it being JSON:
json_data = json.loads('{' + json_file.read().partition('{')[2])
(or use a regex, or whatever you prefer for string manipulation)
You should still beware that JavaScript is not the same as JSON, so you need some confidence that what you're given will always be an assignment of a valid JSON associative array to a variable.
If, on the other hand, you're being passed arbitrary JavaScript and you're expected to evaluate it, then you have a much bigger problem to solve. What if someone gives you var xyz = "Monthly"; var abc = {"label" : xyz, "URL" : "xyz" + "." + "com"}?
You need a JavaScript engine to solve that more general problem, not just a JSON parser. For example, js2py claims to be a complete JavaScript engine written in Python, but I've never used it so I can't recommend or dis-recommend it.
There are also security issues to consider in executing code from untrusted sources, beyond those you consider if all you're doing is parsing JSON from an untrusted source. So if you need to use a JavaScript engine, make sure you properly understand how it is sandboxed.
Your code is Javascript, not JSON...
With this code in JS you just create a new Object.
But JSON IS NOT A LANGUAGE!!.!
Json is a solution to efficiency store/transmit datas (as assiocative arrays).
Just try to do not define abc:
Your JSON file:
{
"a" :
{
"label": "Monthly",
"URL": "xyz.com",
"ArchTag": "M",
"archData":
{
"Feb 2016":"20160229",
"Jan 2016":"20160129",
"Dec 2015":"20151231"
}
}
}
If you can not remove var abc of your file, read the file in a string, remove the first characters of the string and load the new string.
try:
with open(file) as json_file:
data = file.read()
json_data = json.loads(data[9:])
pprint(json_data)
except Exception as e:
print(e)
if it is not always written var abc then start your string at the first { index.
Actually the file content is not json because of the var you mentioned. you should remove that part dynamically:
json_text = json_file.read().replace('var abc=','')
json_data = json.dumps(json_text)
pprint(json_data)
You can use regex to replace the var assignment piece:
with open('file.txt') as json_file:
data = json_file.read()
data = re.sub(r'^var\s*\S*\s*=\s*', '', data)
json_data = json.loads(data)
I want to ask because I doubt it. Can I put a JSON inside JSON? Like this.
var json = {
test = { "name":"test", "age":"99" };
};
So I can use it like this :
console.log(json.test.name);
Thank you for your answer.
Yes, your syntax is just wrong:
var json = {
test: { "name":"test", "age":"99" }
^^ ^^ no semi-colon
};
And for clarification, what you have is a Javascript Object Literal, not JSON. JSON is a string representation of a Javascript Object**
** Simplified explanation. Full details http://json.org/
Please correct your json :
var jsonVar = {test :{ "name":"test", "age":"99" }};
Also avoid creating a variable using reserved words like json. use jsonVar, jsonVal etc.
console.log(jsonVar);
console.log(jsonVar.test);
console.log(jsonVar.test.name);
console.log(jsonVar.test.age);
and their respective ans in firebug console.
Object { test={...}}
Object { name="test", age="99"}
test
99
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.