Following json string is not converting into json as key is not inside quote.
{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}
I have tried:
JSON.parse -- it does not work as keys are not inside quotes.
eval('('+str+')') -- not converting for some reason, also little reluctant for this solution due to security.
Manually insert double quotes delimiting colon (:) but one of my
value, which is a url, too has a colon, as given in the solution:
regular expression add double quotes around values and keys in javascript
Why is it difficult to convert this string into json and how to convert it?
var s = '{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}';
console.log(eval('(' + s + ')'));
The main question is really where did you get the string from, but anyways, here is a solution.
var obj = eval('(' + str + ')');
var json = JSON.stringify(obj);
Related
I am hoping to get some insight into this issue I am having. I couldn't really find any other questions like this doing the same thing. I am using python 3.7.
I am pulling in contents of strings using regex which then will replace other parts of a JavaScript file I am reading in. I am familiar with raw strings when reading data in, but when I go to replace certain parts containing the double backslash only one is printed. I know it is escaping the string due to the backslash on the \", but I am at a loss with this. Adding a third "\" to it making it "\\\" will solve the issue, but I cannot do that due to the type of data I am working with.
For example, I want to replace all instances that the string "Ch" is found in a file I am reading in with "\\" using regex. This new data is then outputted to a new file.
How do I go about replacing certain content with the string '"\\"' ensuring that nothing is escaped and only "\\" is outputted?
Simplified sample code for testing:
string = R'"\\"'
Converted_Text = re.sub("Ch", ' ' + string, Converted_Text)
with open('output.js','w') as w:
w.write(Converted_Text.strip().replace('\n',''))
Sample file being read in:
var test = Ex("Temp") + Ch + wn;
var num1= 1;
var num2 =2;
var sum = num1+num2;
var blah, meh;
You can first replace CH with \\CH and again replace CH with \\.
How do I parse an array of objects if it contains single quote characters?
For example, I have:
$example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
The single quotes seem to break up the array, making parsing impossible.
You can use backticks (``). It will generate the string as it was written, with double "" and single ' quotes.
var str = `{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}`;
console.log(str);
var obj = JSON.parse(str);
console.log(obj.response[0].uid);
It's a json string not an object.
Use JSON.parse(myJsonSting) and you will get objects with the ' taken care of.
Javascript is supposed to ignore single quotes if it is inside double quotes, in your case try adding backslash before the single quote.
To parse at json string to object
var example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
var objExample = JSON.parse(example);
To convert json object to json string
var StrExample = JSON.stringify(objExample);
this is my string,
var str=""{\"checkedRows\":\"[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]\",\"checkedIndex\":\"[0]\"}"";
I'm trying to get substring as below
[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]
And i'm trying below code to split
var newStr = str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("]"))
but unable to fetch it.
Firstly note that you have an extra leading and trailing double quote around your JSON string. Secondly the JSON itself is completely malformed. You need to fix the errors it has (extra/mis-matched double quotes mostly) so it looks like this:
'{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}'
Once you've done that you can parse the string to an object, then retrieve the checkedRows property and stringify that again, like this:
var str = '{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}';
var obj = JSON.parse(str);
var newStr = JSON.stringify(obj.checkedRows);
console.log(newStr);
I have a string
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
How can I parse the above string (str) into a JSON object ?
This seems like a simple parsing. It's not working though.
The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.
I know it's an old post, but you can use JSON5 for this purpose.
<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works.
Eval is not evil when it is used on data you have control over.
For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
For your use-case perhaps this would be the easiest solution:
str = '{"a":1}';
Source:
If a property requires quotes, double quotes must be used. All
property names must be surrounded by double quotes.
var str = "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);
This solved the problem for me.
Something like this:
var div = document.getElementById("result");
var str = "{'a':1}";
str = str.replace(/\'/g, '"');
var parsed = JSON.parse(str);
console.log(parsed);
div.innerText = parsed.a;
<div id="result"></div>
// regex uses look-forwards and look-behinds to select only single-quotes that should be selected
const regex = /('(?=(,\s*')))|('(?=:))|((?<=([:,]\s*))')|((?<={)')|('(?=}))/g;
str = str.replace(regex, '"');
str = JSON.parse(str);
The other answers simply do not work in enough cases. Such as the above cited case: "title": "Mama's Friend", it naively will convert the apostrophe unless you use regex. JSON5 will want the removal of single quotes, introducing a similar problem.
Warning: although I believe this is compatible with all situations that will reasonably come up, and works much more often than other answers, it can still break in theory.
sometimes you just get python data, it looks a little bit like json but it is not. If you know that it is pure python data, then you can eval these data with python and convert it to json like this:
echo "{'a':1}" | /usr/bin/python3 -c "import json;print(json.dumps(eval(input())))"
Output:
{"a": 1}
this is good json.
if you are in javascript, then you could use JSON.stringify like this:
data = {'id': 74,'parentId': null};
console.log(JSON.stringify(data));
Output:
> '{"id":74,"parentId":null}'
If you assume that the single-quoted values are going to be displayed, then instead of this:
str = str.replace(/\'/g, '"');
you can keep your display of the single-quote by using this:
str = str.replace(/\'/g, '\'\');
which is the HTML equivalent of the single quote.
json = ( new Function("return " + jsonString) )();
We're already aware that we cannot add double quotes inside the double quotes:
var str = ""hello""; //this will be invalid string
but when I stringify an object like this
var obj = {"name":"abc"}
var str = JSON.stringify(obj).
str // returns "{"name":"abc"}"
which is valid but shouldn't be. I'm confused as in do JavaScript have some special cases when we stringify a JSON object and omit the string validations on it?
Thanks in advance.
You can have as many double quotes inside a string literal as you want. You just need to scape them using a backslash prefix (\" instead of ").
Try this example in your browser console:
var myStr = "\"Hello\"";
myStr
You should see ""Hello"" in your console. That would be how the stringify creates a string with double quotes in it.