Javascript / Chrome - How to copy an object from the webkit inspector as code
Solution 1:
-
Right-click an object in Chrome's console and select
Store as Global Variable
from the context menu. It will return something liketemp1
as the variable name. -
Chrome also has a
copy()
method, socopy(temp1)
in the console should copy that object to your clipboard.
Note on Recursive Objects: If you're trying to copy a recursive object, you will get [object Object]
. The way out is to try copy(JSON.stringify(temp1))
, the object will be fully copied to your clipboard as a valid JSON, so you'd be able to format it as you wish, using one of many resources.
If you get the Uncaught TypeError: Converting circular structure to JSON
message, you can use JSON.stringify
's second argument (which is a filter function) to filter out the offending circular properties. See this Stack Overflow answer for more details.
Solution 2:
In Chrome 89 or later you can simply right click an object in the console and choose Copy Object
(ref). This also works in some other places inside Chrome Developer Tools e.g. whilst debugging or inside response tab for a network request.
Other option is to use the copy
command as-is:
var x = { a: 1, b: 2 };
copy(x);
Original answer
Solution 3:
You can copy an object to your clip board using copy(JSON.stringify(Object_Name)); in the console.
Eg:- Copy & Paste the below code in your console and press ENTER. Now, try to paste(CTRL+V for Windows or CMD+V for mac) it some where else and you will get {"name":"Daniel","age":25}
var profile = {
name: "Daniel",
age: 25
};
copy(JSON.stringify(profile));
Solution 4:
You can now accomplish this in Chrome by right clicking on the object and selecting "Store as Global Variable": http://www.youtube.com/watch?v=qALFiTlVWdg
Solution 5:
Follow the following steps:
- Output the object with console.log from your code, like so: console.log(myObject)
- Right click on the object and click "Store as Global Object". Chrome would print the name of the variable at this point. Let's assume it's called "temp1".
- In the console, type:
JSON.stringify(temp1)
. - At this point you will see the entire JSON object as a string that you can copy/paste.
- You can use online tools like http://www.jsoneditoronline.org/ to prettify your string at this point.