convert json_encode php to javascript but without double quotes - javascript

here is the output of a php json_encode() call:
//start
//docStructure version 1.0.alpha compiled September 16th, 2014 at 9:18PM
var docStructure={"updateTime":"2014-09-16 21:18:19","listeners":[{"name":"eFaxListener","active":"0","url":"?action=faxvcheckinboundfax"}],"sections":{"defaultLayout":{"header":[]}},"editors":{"sideeditor":{"state":"closed","width":"0","context":""}}}//end
note the keys all have double quotes around them.
I would prefer to have the keys NOT have double quotes for easier reading. Is there any difference? I would prefer to identify as
alert(docStructure.editors.siteeditor.state);
vs.
alert(docStructure['editors']['siteeditor']['state'])
Or can I stil use these interchangeably with the keys as strings?
Thanks, this is building my understanding of javascript's thinking..

The JSON format requires the keys to be double quoted, once parsed by javascript its just a normal object, so you can access them both ways, assuming your keys are valid object keys(not starting with a number or a special character).

You are looking for jQuery.parseJSON( json )
Description:
Takes a well-formed JSON string and returns the resulting JavaScript object.

Related

How to convert string to object in javascript?

const str="{a:{url:'http://localhost:80',c:1,},d:'d',e:true}"
How to get the result without using evil and new Function:
const obj={a:{url:'http://localhost:80',c:1,},d:'d',e:true}
First of all:
You need to format your string into a valid JSON format ( double quotes instead of single quotes )
And then you'll just need to JSON.parse(str)
To convert a string to json you can use JSON.parse(str)
But first make sure the string syntax is correct, there are several websites to do this, one of many is this https://jsonlint.com/

Converting JSON strings with escaped Unicode characters to JavaScript objects

I have a JSON string which contains an escaped Unicode character. The JSON includes this snippet:
I co-ordinate our Chat Literacy network \u2013 an online group for practitioners of Information Literacy
The \u2013 is a long dash.
I'm using
var theObject = eval ("(" + jsonString + ")");
to convert the JSON string to a JavaScript object. I need to use a version of SpiderMonkey that doesn't have a direct JSON to Object method in it.
After conversion, the character in question becomes the Unicode control character \0013 which is an invalid UTF-8 character.
Is there another way I can convert the JSON to an object which will preserve the correct long-dash character? Maybe some other JSON to Object method I can load?
This happens with some other characters also, like curly quotes.
Thanks,
Doug
eval() is evil. Stay away from it.
Try using JSON 3: http://bestiejs.github.io/json3/

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"

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.

Parse nested function call string in javascript

I want to parse the following string (using Javascript):
color(alias(sumSeries(sys.mem.free.*),"memory (free)"),"#00AA88")
into an array of function names and arguments:
[["color", "#00AA88"],
["alias", "memory (free)"],
["sumSeries", ""]]
plus extract the innermost string
sys.mem.free.*
The string is actually the target parameter from graphite.
I don't want to write a parser myself (dealing with things like double quotes and brackets is hard to get right).
Is there a library which helps with basic parsing?
Since it's not JSON I cannot go for a JSON parser.

Categories

Resources