correctly adding to json from javascript - javascript

hi im having trouble correctly adding to my json
here is the code.
When i console.log the string im trying to add is
{"type":"#","name":"wh2xogvi","list":[{"0":"background-color"},{"1":"border"},{"2":"width"}, {"3":"height"},{"4":"margin"}],"listvalues":[{"0":"#aaa"},{"1":"2px solid #000"},{"2":"1040px"},{"3":"50px"},{"4":"0 auto"}]}
it is valid json
var jsonltoload = JSON.stringify(eval("(" + jsonloadtostring + ")"));
console.log(jsonltoload); // this is the console log i was talking about higher up
fullJSON.styles.objectcss.push(jsonltoload);
But when i actually look at the json it is wrong ends up something like this
"{\"type\":\"#\",\"name\":\"unkd42t9\",\"list\":[{\"0\":\"background-color\"},{\"1\":\"border\"},{\"2\":\"width\"},{\"3\":\"height\"},{\"4\":\"clear\"}],\"listvalues\":[{\"0\":\"#ddd\"},{\"1\":\"2px solid #000\"},{\"2\":\"100%\"},{\"3\":\"50px\"},{\"4\":\"both\"}]}",
the fullJSON comes from JSON.parse(json); which comes from a file

You seem to confuse JSON, a textual, language-independent data representation, with JavaScript objects, a language-specific data type.
JSON.stringify returns a string (containing JSON), so jsonltoload is a string. I guess you simply want to parse the JSON and add the resulting object:
var obj = JSON.parse(jsonloadtostring);
fullJSON.styles.objectcss.push(obj);

I think the JSON string is trying to escape the double quotes character you have added to string, resulting in the string. try to enclose the whole string with single quotes rather than double quotes

Related

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

How to convert JSON Parse object property into array?

In mysql database, "diagID" is saved as json_encoded(array). Now i need it to retrieve in ajax success.
How to convert JSON parse data into array, as it's showing string?
var ajaxResponse= {
"id": "123",
"diagID" : "['101','125','150','230']"
}
typeof(ajaxResponse.diagID)
= string
In javascript typeof(ajaxResponse.diagID) shows string. How to convert it into array?
Decoding it in php would make most sense
$diagID = json_decode($diagID, true);
Then when you json_encode() the whole response it won't have the extra wrapping quotes.
Note however that the strings in array have single quotes which are not valid json and need to be replaced with double quotes before they can be parsed in either language

How to handle JSON string errors (error character ") in javascript

An administrator has directly filled content into the database and formatted it as json string. However, when retrieving it from the database and parse it into json, it failed. Because when filling data directly, instead of content need to write this (\"), they just write (") the json string shield is faulty and cannot parse. How to solve this problem.
Ex:
"aaaa"dddd"aaaa" => "aaaa\"dddd\"aaaa"
I assume that when you retrieve the string from the database, you are getting something like: '"aaaa"dddd"aaaa"'
If so, then you can convert that to a valid JSON string by removing the first and last double quotes and using JSON.stringify to convert the string to a valid JSON string (including escaping the inner double quotes).
For example:
const s = '"aaaa"dddd"aaaa"';
const escaped = JSON.stringify(s.slice(1, -1));
console.log(escaped);
// "aaaa\"dddd\"aaaa"
const parsed = JSON.parse(escaped);
console.log(parsed);
// aaaa"dddd"aaaa
You might use replace with RegExp and g flag
let str = `"aaaa"dddd"aaaa"`;
let result = str.replace(/"/g,`\\"`).slice(1,-2) + '"';
console.log(result)
OP asked My database return result string "aaaa"dddd"aaaa", How to assign such "aaaa"dddd"aaaa"
You can interpolate that return from database into Template Strings
let str = `${database.value}`;
Not sure what database or what language is on server side, however, rather that trying to escape the inner quotes. Trying just replacing the first and last double quote with with a single quote. Not sure of the full context here to know whether this is the issue. Anyway, something to consider

How to convert formatted string to regularly javascript dictionary?

I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ?
I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents.
Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

Parsing JSON with special characters

I am using flot to do some graphing and I am having some trouble passing the tickSize with my json. I am using MVC and pass the json in a model. Here is some code to grab the json within my javascript function:
var json = '<%=Model.Json %>';
var data = jQuery.parseJSON(json);
Here is how the Json looks leaving the controller:
{\"GraphData\":[{\"X\":1333929600000,\"Y\":0.0},{\"X\":1333670400000,\"Y\":0.46}],\"Max\":1333324800000,\"Min\":1333929600000,\"TickSize\":\"[1, 'day']\"}
The part that I am having trouble with is "TickSize." As you can see, "[1, 'day']" has the square brackets. I think there is some parsing problem because [] usually means an array. Flot wants the tick size in this format. How do I construct my Json so I can grab the TickSize?
The issue is the single-quotes in the string value, since you're trying to wrap the JSON string in them as well. The resulting JavaScript will be (truncated):
var json = '...,\"TickSize\":\"[1, 'day']\"}';
Because of the now 4-count of single-quotes, day isn't actually part of the string and creates a syntax error.
But, you shouldn't even need to quote and parse the JSON since it's derived from JavaScript syntax:
var data = <%= Model.Json %>;
If you need the string representation, you can either stringify it in JavaScript:
var json = JSON.stringify(data):
Or escape single-quotes within the string server-side:
var json = '<%= Model.Json.Replace("'", "\\'") %>';
It is because you have surrounded the string with ' instead of ". This is causing the string to terminate with your first '.
Rewrite your first line as
var json = "<%=Model.Json %>";
Solution : replace single backslash '\' with double '\\' back slash.
For Newline character '\n' to '\\n'
Works with Tooltip messages

Categories

Resources