Unable to access a key value from a json - javascript

I have a json as below
var object = {200x200: "url1", 400x400: "url2", 800x800: "url3"};
I stringified the object and tried to acccess "200x200". But its throwing
undefined
object = JSON.stringify(object);
//object = {"200x200": "url1", "400x400": "url2", "800x800": "url3"};
I tried to access like this
object['200x200'] // got undefined
Any other way to access the url1 from this object ?

Because you json object is wrong format:
Wrap your keys in quotes, like this: https://codepen.io/creativedev/pen/LrBOmG
var object = {'200x200': "url1",'400x400': "url2", '800x800': "url3"};
Then check:
console.log(object['200x200']);
you will get output

Once you stringify it, it’s a string. You have to parse it back into an object.
var newObject = JSON.parse(object);
console.log(object[200x200];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

you should change you object to
var object = {'200x200': "url1", '400x400': "url2", '800x800': "url3"};
object['200x200'] // 'url1'

You can parse it:
object = JSON.parse(object);
then access the key:
let url1 = object['200x200']
No idea why you would stringify it in the first place though!
let jsonObject = JSON.stringify(object);
// instead of:
let url1 = JSON.parse(JSON.stringify(object))['200x200']

Related

How to pass variable to JSON without printing it as String

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!

How to access part of string contained in an object in Javascript

I have an object that looks like this
{'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' }
I want to access part of what's contained in it
For example, if it was a normal object I would've thought I could do
objectName.variable
or
objectName.["variable"]
First of all, You should parse json data.
var obj = JSON.parse('{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}');
console.log(obj.variable);
console.log(obj.text);
etc ...
Firstly, parse the JSON - then because the data is a key, use Object.keys, then get the variable property:
const obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
const { variable } = JSON.parse(Object.keys(obj)[0]);
console.log(variable);
var obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
// get keys from obj
var keys = Obejct.keys(obj);
// loop keys array
keys.forEach((item) => {
// !!! parse String to JSON !!!
var parsedObj = JSON.parse(item);
console.log(parsedObj.variable);
})

Javascript Inserting an object "inside"(each index having object already) an array of objects

I hava a json response like [{0},{1},{2}..] and each index contains object data. I also have an object like a{} which also contains object data.What I want is to add the object a "inside"(at the end) the each index like [{0..a},{1..a},{2a}].
Parse the json response using JSON.parse then iterate over it and add the object inside each object
var resp = '[{"data":"1"},{"data":"2"},{"data":"3"},{"data":"4"}]';
var arr = JSON.parse(resp);
console.log(arr);
var a = {
data: 5
};
arr.forEach(function(element,i) {
arr[i].a = a;
});
console.log(arr)
So assuming your json response is in some variable (let's say its called jsonResponse) and a is an Object you can do:
jsonResponse.push(a)
Which will add the a object to the end of the jsonResponse array.
This assumes that jsonResponse is an array, if it is a string you may have to do something like:
let jsonResponse = JSON.parse(responsestring)
Your question is not totally clear, but sounds like you want to look at array.map.
For example:
let arr = [{x:1,y:2},{x:3,y:4}];
const foo = arr.map(obj=>{obj.z=42; return obj})
console.log("GOT:", foo);
to combine two json objects:
function combineObj(ob1, ob2) {
return Object.fromEntries(Object.entries(ob1).concat(Object.entries(ob2)));
}
var a = [{b:1},{q:3},{s:2}],
b = {a:2};
var result = a.map(x=>combineObj(x,b));
console.log(result);
From what I understand you want to add Object A to every Object in your JSON response?
If so try:
var jsonResponse = [{a: 1}, {a: 1}, {a: 1}]
var objToAppend = {b:2}
for(var objectInJsonResponse of jsonResponse){
objectInJsonResponse.appendedObject = objToAppend;
}
This will result in:
console.log(jsonResponse)
[{a:1,appendedObject:{b:2}},{a:1,appendedObject:{b:2}},{a:1,appendedObject:{b:2}}]
Of course you can change the name of appendedObject to whatever you want the key to be.

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>

Converting a string to JSON object

How do you make JS think that a string is JSON ?
I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.
I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.
So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.
The string is as follows:
{
"data": [
{
"id": "id1",
"fields": [
{
"id": "name1",
"label": "joker",
"unit": "year"
},
{"id": "name2", "label": "Quantity"},
],
"rows": [ data here....
and closing braces..
var obj = JSON.parse(string);
Where string is your json string.
You can use the JSON.parse() for that.
See docs at MDN
Example:
var myObj = JSON.parse('{"p": 5}');
console.log(myObj);
I had the same problem with a similar string like yours
{id:1,field1:"someField"},{id:2,field1:"someOtherField"}
The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the [] with this the parser recognized
var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)
Hope it helps,
If anyone has a more elegant approach please share.
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
link:-
http://api.jquery.com/jQuery.parseJSON/
Simply use eval function.
var myJson = eval(theJsibStr);
convert the string to HashMap using Object Mapper ...
new ObjectMapper().readValue(string, Map.class);
Internally Map will behave as JSON Object
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
Let's us consider you have string like
example : "name:lucy,age:21,gender:female"
function getJsonData(query){
let arrayOfKeyValues = query.split(',');
let modifiedArray = new Array();
console.log(arrayOfKeyValues);
for(let i=0;i< arrayOfKeyValues.length;i++){
let arrayValues = arrayOfKeyValues[i].split(':');
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
modifiedArray.push(arrayString);
}
let jsonDataString = '{'+modifiedArray.toString()+'}';
let jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
console.log(typeof jsonData);
return jsonData;
}
let query = "name:lucy,age:21,gender:female";
let response = getJsonData(query);
console.log(response);
`
JSON.parse() function will do.
or
Using Jquery,
var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
JSON.parse() is your friend. Here's an example:
let obj = JSON.parse(yourString)
console.log(typeof obj); // prints 'object' assuming your string is correctly formatted

Categories