How to pass variable to JSON without printing it as String - javascript

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!

Related

How I can filter a value corresponding to a specific key in a string?

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'

Fetch key inside a json object in php jquery

I am returning a json data to jquery using php. what i want is to access the keys inside the json. i followed a tutorial and used json stringify but im not able to access the keys.
json data :
[
{"id":"1","movie_name":"spiderman","releases_on":"20th August 2018"},
{"id":"2","movie_name":"batman","releases_on":"21st August 2018"},
{"id":"3","movie_name":"fast and furious 6","releases_on":"22nd August 2018"}
]
code in jquery:
var json = data;
var obj = JSON.stringify(json);
console.log(obj[1].id);
you have to use JSON.parse(json).
then, you can do it.
JSON.stringify() will take your JSON object and convert it to a JSON string (here which is response).
JSON.parse() will take stringified JSON and convert it to object so that you can access via . operator
for example,
var a = { name: "John", age: 20 }
console.log(typeof a) // object
var out = JSON.stringify(a)
console.log(typeof out) // string
var res = JSON.parse(out)
console.log(typeof res) // object
I hope you got it....

Get data from this json string

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/

How to get values from JSON object

I have a string with values i want to use. I'm parsing this string as an JSON object using $.parseJSON. However I'm having problems getting the actual values.
In this case I'm trying to get the value of the key "textarea1" which is "banana". What is the correct syntax for getting the values. I tried obj.texts.textarea1, but it didn't work.
The string looks like this:
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
Script:
var oldVal = $.parseJSON(obj);
missing quote on \Apple
You access obj but need to access oldVal
you have nested arrays so you need array notation to get at them or flatten the arrays
You do not need jQuery and likely have not defined it. JSON.parse will work
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
var oldVal = JSON.parse(obj);
console.log(oldVal[0].texts[0].textarea1)
If you want to access oldVal.texts.textarea1 you need to remove the array:
var obj = "{\"texts\":{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}}";
1st Option
You need not to change anything. Just fix your JSON in correct format.
You can use JsonLint to check your JSON is correct or not. Then Proceed further.
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
var oldVal = JSON.parse(obj);
alert(oldVal[0].texts[0].textarea1)
2nd Option
If you want to get the result like obj.texts.textarea1 then you'll have to change your data as following.
Format Your JSON
Remove all [ and ] from your json.
then do.
var a = '{"texts": {"default": true,"bread-texts": false,"textarea1": "Banana","textarea2": "Kiwi","textarea3": "Apple","textarea4": "coffe","textarea5": "Tea","signature": true,"profile": "header","fontsize": "26","fontsize-headers": "10.5","fontcolor": "#0000","textfont": "header-large","textsub1": "Bold","font": "ICA%20Text","textsub": "Regular","textsize": "20","textsize-signature": "9.5","textsizesmall": "5.5","textsizesmall-placer": "2.75","vers-placer": "false","text-colored": "%23000000","s-all-customers": true,"new-customers": true,"undefined": ""} }';
var obj = JSON.parse(a);
Then
obj.texts.textarea1;
You've created array in your JSON so for that you need to do array accessing.
obj is of type string. You can not index it as object in the form obj.texts. You are parsing it using $.parseJSON, then use the object returned by that call:
var oldVal = $.parseJSON( obj );
var value = oldVal[0].texts[0].textarea1;
Your JSON is invalid.
At this place, you are missing a quote:
\"textarea3\":\Apple\" (escaped)
"textarea3":Apple" (unescaped)
JSON parsing will fail at this point.
After fixing this typo, I can easily access your JSON items this way:
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
// using JSON.parse
document.body.innerHTML = JSON.parse(obj)[0].texts[0].textarea1;
// or using jQuery
document.body.innerHTML += $.parseJSON(obj)[0].texts[0].textarea1;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to convert JSO to JSON?

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)

Categories