I have example :
var data = [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]
I want to convert jso above to json like this result :
[{name:"eric",age:24},{name:"goulding",age:23}]
Please give me advice.
You need to use JSON.parse with a reviver parameter:
var jsonString = '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]';
// given a string value, returns the number representation
// if possible, else returns the original value
var reviver = function (key, value) {
var number = Number(value);
return number === number ? number : value;
};
// because the reviver parameter is provided,
// the parse process will call it for each key-value pair
// in order to determine the ultimate value in a set
var data = JSON.parse(jsonString, reviver);
When the reviver is called with reviver("name", "eric"), it returns "eric" because "eric" cannot be converted to a number. However when called with reviver("age", "24"), the number 24 is returned.
Meanwhile, as others already noted the literal [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}] is not JSON, it is an array. But the string '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]' represents a valid JSON formatted array object.
let data = [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]
This is JSON and in order to convert it to a JavaScript object (jso) we need to use parse. If we want to manipulate JSON, we convert JSON to JSO using JSON.parse.
let convertedToJSO = JSON.parse(data)
let data = [{name:"eric",age:24},{name:"goulding",age:23}]
And this is a JSO. If you want to print or save JSO, convert JSO to JSON using JSON.stringfy.
let convertedToJSO = JSON.stringfy(data)
Related
How to pass variable to JSON object and print it like JSON object?
I simply want to pass variable value in JSON and print it like JSON which can also be used in console.table(obj)
With Stringify:
var name = "someName";
const json = JSON.stringify('{"result":'+name+', "count":42}');
const obj = JSON.parse(json);
console.log(obj);
Without stringify
var name = "someName";
const json = '{"result":'+name+', "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Using \"variableName\" it gets value in \"...\" and not the variable value
var name = "someName";
const json = '{"result":\"name\", "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Solution:
var debugJSON = [];
var section_number = 1;
var i = 25;
var x = section_number-i;
tempJSON = {
"section" : section_number,
"index" : i,
"fieldname" : x,
"isValid" : "not required"
};
debugJSON.push(tempJSON);
console.log(debugJSON);
//console.table(debugJSON); //Problematic on Chrome Browser and Stack Overflow
JSON is a text representation of some data structure.
Unless you write a JSON encoder (and you don't), you don't have any reason to produce JSON manually. Attempting to generate JSON using string concatenation fails if the variable strings (name in this case) contain quotes or backslash. Escaping them could produce valid results but the code becomes bloated and difficult to read without any gain.
JavaScript provides the method JSON.stringify() to produce a JSON from any data and this is the best way to generate JSONs.
All you have to do is to build the data structure that you need to encode. In your example, the data structure is an object:
let name = "someName";
const original = {
result: name,
count: 42,
}
// encode
const json = JSON.stringify(original);
console.log(json);
// decode
data = JSON.parse(json);
console.log(data);
Running the code snippet here in page is not relevant because the output that it produces looks similar for both calls of console.log().
Run the code using Node.js or run it in the browser's console to see the values of json (it is a string) and data (it is an object).
A JSON is quite literally a JavaScript object, so you don't treat it as a string, you work with objects, which you can later stringify if need be.
In your case, you don't want to pass a variable in a string, you should pass it in an object like so:
// Declaration of name
let name = 'someName';
// Create object and store name
const json = {
result: name,
count: 42
};
// Log object as JSON and as string
console.log(json);
console.log(JSON.stringify(json));
The first log returns your object as exactly that, an object, the second log, converts it into a string to do so as you please with it!
In my JS code, i have string as
s = "{\"selector\":{\"owner\":\"tom\"}}"; // originally this is a query response
I want to extract the value of 'owner' which is tom in another variable, s1.
What would be the easiest way to do it?
To convert your data to an object use obj = JSON.parse(s)
Then obj.selector.owner Or
obj["selector"]["owner"] which is the recommended way to get JavaScript object values...
You are not selecting the right properties when accessing your response data. Also you do not need to use toString in JSON.parse. Because your response is already a string data.
You want to convert string data by using JSON.parse
Demo:
//Response # 1
let findOwner = "{\"selector\":{\"owner\":\"tom\"}}"
//Parse Data
let parseData = JSON.parse(findOwner)
console.log(parseData.selector.owner) //Tom
//Response # 2
let findOwner2 = "{\"response\":{\"colour\":\"black\",\"make\":\"Tesla\",\"model\":\"S\",\"owner\":\"Adriana\"}}"
//Parse Data
let parseData2 = JSON.parse(findOwner2)
console.log(parseData2.response.owner) //Adriana
You can use a function for this:
function get(path, obj) {
return path.split('.').reduce((acc, current) => acc && acc[current], obj)
}
const obj = "{\"selector\":{\"owner\":\"tom\"}}"
const parsed = JSON.parse(obj)
get('selector.owner', parsed) // return 'tom'
👋 I need a little bit of help to understand JSON better.
When I stringify an array with class objects then parse it back, it looks like the array loses the class instance. Can I keep the class even after parse JSON data, and if can, how? And why does this happen?
Here is the code:
class Account {
constructor(site, login, pass) {
this.site = site,
this.login = login
this.pass = pass
}
}
const accounts = [
new Account("website1.com", "email1#gmail.com", "12345"),
new Account("website2.com", "email2#gmail.com", "23456")
]
console.log('BEFORE', accounts)
const string = JSON.stringify(accounts)
console.log(string)
const parseString = JSON.parse(string)
console.log('AFTER', parseString)
The console shows like this:
BEFORE (2) [Account, Account]
{string: "[{"site":"website1.com","login":"email1#gmail.com"….com","login":"email2#gmail.com","pass":"23456"}]"}
AFTER (2) [{…}, {…}]
To make things clear, is it possible to have [Account, Account] after JSON.parse()`?
Let me know if my explanation is not clear.
Thank you so much!
JSON has no support for types other than object, array, null, string, number and boolean.
If you kind of know what you can expect in your JSON, you can use a reviver function during parsing. For your example, this suffices:
JSON.parse(string, (k, v) => v.hasOwnProperty('site')
? new Account(v.site, v.login, v.pass)
: v);
JavaScript has two useful methods to deal with JSON-formatted content:
JSON.stringify() & JSON.parse(), which are useful to learn as a pair.
JSON.stringify() takes a JavaScript object and then transforms it into a JSON string.
JSON.parse() takes a JSON string and then transforms it into a JavaScript object.
What I understood from your question is that, you want your parsed JSON String converted into your Account Object Prototype. To achieve you could use the below code since JSON.parse() returns Javascript object which we explicitly need to convert to our custom object prototype ( i.e. Account in your case).
const string = JSON.stringify(accounts)
console.log(string);
const parseString = JSON.parse(string);
objectFromJson = function (parseString){
var temp = [];
for( var i = 0; i < parseString.length; i++) {
temp.push(new Account (parseString[i].site, parseString[i].login, parseString[i].pass));
}
return temp;
};
var accountArray = objectFromJson(parseString);
console.log('AFTER', accountArray);
I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);
I have a json string
["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]
I need to get at the data only and I want to extract the string to get the following :
https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
I have tried to use JSON.parse but this does not seem to work
Any help woul dbe appreciated
[] represents an array on JSON. {} represents an Object.
So in order to fetch the first element from you json string, you have to parse the string as a JSON element ;
var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');
OR when you HAVE a json array already;
var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
Then, go on and fetch the first value from your array which has index 0 as in all programming languages.
var url = arr[0];
It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:
var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
Be aware of the difference between an array, and a JSON object.
I have given some examples of the differences and how to access them.
// This is an array containing 1 value.
myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
// it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value.
var example1 = [myobj];
document.write("This is my single value array:<br>" + example1 + "<br><br>");
// This is probably best practice regardless of the number of items in the array.
var example2 = myobj[0];
document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>");
// This is a JSON object
myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"}
// You access the value of the URL like this:
var example3 = myJsonObj.url;
document.write("Here is the value from a JSON object:<br>" + example3 );
Hope this helps
Just use parse function:
var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);
https://jsfiddle.net/esouc488/1/